使用 MVVM 动态添加时给予 TabItem 焦点 [英] Give a TabItem Focus when Dynamically Adding Using MVVM
问题描述
全部,我正在使用 MVVM 动态地将 TabItem
添加到 TabControl
.新的 TabItems
加载良好,但我希望添加的选项卡自动获得焦点.也就是说,我添加了一个选项卡,但我不想必须单击该选项卡才能获得焦点.
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.
TabControl
的 XAML 看起来像
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>
我认为(基于这里的一些答案),IsSynchronizedWithCurrentItem="True"
会为我解决这个问题,但这不起作用.
I thought (based upon some answers here), that IsSynchronizedWithCurrentItem="True"
would solve this for me, but this is not working.
如何自动选择添加的TabItem
?
感谢您的时间.
推荐答案
您可以将 selectedIndex 绑定到视图模型上的属性
You can bind the selectedIndex to a property on your viewmodel
SelectedIndex="{Binding SelectedTabIndex}" >
或使用
SelectedItem="{Binding SelectedWorkSpace}"
在您的 ViewModel 中,当您向 Workspaces 添加新的 Workspace 时,请适当设置 SelectedTabIndex/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.
这篇关于使用 MVVM 动态添加时给予 TabItem 焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!