Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TabControl - Select different tab when TabItem Visibility changes

Tags:

wpf

I have a TabControl on a UserControl backed by a ViewModel, and the Visibility of one of the tab items is bound to a property on the ViewModel.

<TabControl x:Name="myTabControl">
    <TabItem Header="Tab 1" />
    <TabItem Header="Tab 2" Visibility="{Binding HasData, Converter={StaticResource boolToVisibilityConverter}}"/>
</TabControl>

When the Visibility of the TabItem changes, it collapses (hides) the TabItem header, but it continues displaying its content.

I want the TabControl to switch to the visible tab when the other tab is hidden, and was a little surprised to find out it doesn't happen automatically.

Attaching an event handler to the SelectionChanged event of the TabControl shows that TabItem.IsSelected (and TabControl.SelectedItem) is not even affected when the TabItem.Visibility changes (is this a bug?!).

I've tried both a property trigger:

    <!-- 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>

and a data trigger:

    <!-- 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>

I can't get the triggers to work, and there's no VisibilityChanged event I can handle, so I'm kind of stuck and would appreciate some help.

like image 586
rikoe Avatar asked Aug 26 '10 13:08

rikoe


1 Answers

The TabItem class has an IsVisibleChanged event that you can use.

like image 114
mdm20 Avatar answered Sep 23 '22 02:09

mdm20