Question

All, I am adding a TabItem to a TabControl dynamically using MVVM. The new TabItems load fine, but I want the added tab to gain focus automatically. That is, I add a tab and I do not want to have to click on that tab to give it focus.

The XAML for the TabControl look like

<TabControl ItemsSource="{Binding Path=Workspaces}" 
            IsSynchronizedWithCurrentItem="True" 
            HorizontalContentAlignment="Stretch" 
            VerticalContentAlignment="Stretch"
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Stretch" 
            TabStripPlacement="Top">
<TabControl.ItemContainerStyle>
   <Style TargetType="TabItem">
      <Setter Property="Header" Value="{Binding Path=DisplayName}"/>
      <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      <Setter Property="VerticalContentAlignment" Value="Stretch"/>
   </Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
   <DataTemplate>
      <views:ResourceControl DataContext="{Binding}" 
                             HorizontalAlignment="Stretch" 
                             VerticalAlignment="Stretch"/>
   </DataTemplate>
</TabControl.ContentTemplate>
</TabControl>

I thought (based upon some answers here), that IsSynchronizedWithCurrentItem="True" would solve this for me, but this is not working.

How can I auto-select the added TabItem?

Thanks for your time.

Was it helpful?

Solution

You can bind the selectedIndex to a property on your viewmodel

SelectedIndex="{Binding SelectedTabIndex}" >

or use

SelectedItem="{Binding SelectedWorkSpace}"

In your ViewModel, when you add a new Workspace to Workspaces, set the SelectedTabIndex/SelectedWorkSpace appropriately.

The later gives you access to the current workspace which you will probably need anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top