WPF TabBarControl Setting Focus to element when tab changes

I have a TabControl that is bound to a view model

          <TabControl
             ItemsSource="{Binding Path=ViewModelCollection}" >
             <TabControl.ItemContainerStyle>
                <Style
                   TargetType="TabItem"
                   BasedOn="{StaticResource {x:Type TabItem}}">
                   <Setter
                      Property="Header"
                      Value="{Binding Title}" />
                   <Setter
                      Property="Content"
                      Value="{Binding}" />
                </Style>
             </TabControl.ItemContainerStyle>
          </TabControl>

Each Tab simply contains a View Model Item. I use a data template to display this.

  <!-- View Model Template -->
  <DataTemplate
     DataType="{x:Type local:ViewModelItem}">
     <DockPanel>
        <TextBox Text="I want this to have the focus"/>
     </DockPanel>
  </DataTemplate>

When the current tab is changed i want the focus to be on the textbox (this is a simple example, in my production code i have a datagrid) in the data template. how do i accomplish this?

Answers


I'm not entirely sure you can set the focus on a UIElement when you have the template defined in a DataTemplate. Instead of working directly with the DataTemplate, you could place your DataTemplate's contents in a UserControl and then set the focus on your TextBox procedurally.

<Window.Resources>
  <DataTemplate DataType="{x:Type local:ViewModelItem}">
    <ContentControl Content="{Binding Path=YourProperty}" />
  </DataTemplate>
</Window.Resources>


<TabControl ItemsSource="{Binding Path=ViewModelCollection}">
  <TabControl.ItemContainerStyle>
    <Style
       TargetType="TabItem">
        <Setter
          Property="Header"
          Value="{Binding Path=Title}" />
    </Style>
  </TabControl.ItemContainerStyle>
</TabControl>

And in the Code Behind of the UserControl:

public MyUserControl()
{
  InitializeComponent();
  this.Loaded += new RoutedEventHandler( OnLoaded );
}

void OnLoaded( object sender, RoutedEventArgs e )
{
  MyTextBox.Focus();
}

I worked up a small project and by pushing the DataTemplate into the UserControl, the TextBox gained focus when the tab was changed.


Need Your Help

PDF generated with PDFBox is blank

java pdf-generation pdfbox java-api

I am trying to write content into a PDF file. I have written the code

Dictionary Behaves Strangely During Databinding

asp.net multithreading caching data-binding dictionary

I was trying to do a little data access optimization, and I ran into a situation where a dictionary appeared to get out of sync in a way that should be impossible, unless I'm somehow getting into a