Give a TabItem Focus when Dynamically Adding Using MVVM

对着背影说爱祢 提交于 2019-12-11 03:46:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16659592/give-a-tabitem-focus-when-dynamically-adding-using-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!