views:

192

answers:

1

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?

A: 

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.

Metro Smurf