我在一个由ViewModel支持的UserControl上有一个TabControl,其中一个选项卡项的可见性绑定到ViewModel上的一个属性。
<TabControl x:Name="myTabControl">
<TabItem Header="Tab 1" />
<TabItem Header="Tab 2" Visibility="{Binding HasData, Converter={StaticResource boolToVisibilityConverter}}"/>
</TabControl>
当
TabItem
的可见性改变时,它会收起(隐藏)TabItem
标题,但它仍然显示其内容。我希望
TabControl
在其他选项卡被隐藏时自动切换到可见的选项卡,但惊讶地发现它不会自动执行。通过将事件处理程序附加到
TabControl
的SelectionChanged
事件,可以看到TabItem.IsSelected
(以及TabControl.SelectedItem
)甚至没有受到TabItem.Visibility
更改的影响(这是一个错误吗?!)。我尝试了属性触发器:
<!-- This doesn't compile because of TargetName on the Setter, think you can only use it in Control Templates.
I don't know how to refer to the parent TabControl from within the TabItem style. -->
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}" BasedOn="{StaticResource {x:Type TabItem}}">
<Style.Triggers>
<Trigger Property="Visibility" Value="Collapsed">
<Setter TargetName="myTabControl" Property="SelectedIndex" Value="0" />
</Trigger>
</Style.Triggers>
</Style>
</TabControl.ItemContainerStyle>
还有一个数据触发器:
<!-- This doesn't quite work, it affects the Visibility of the TabItem's content too -->
<TabControl.Style>
<Style TargetType="{x:Type TabControl}" BasedOn="{StaticResource {x:Type TabControl}}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SelectedItem.Visibility, ElementName=tabControl}"
Value="Collapsed">
<Setter Property="SelectedIndex" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.Style>
我无法使触发器起作用,并且没有VisibilityChanged
事件可以处理,所以我有点困惑并需要帮助。