问题
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