Dynamically hide a WPF TabItem

hardywang picture hardywang · Feb 19, 2016 · Viewed 7.6k times · Source

Let's say I have a very simple XAML

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TabControl>
            <TabItem Header="Tab 1" Visibility="Hidden">
                <TextBlock>shfsdjkfhksh jkfhd sfjdklh sfjdkh fjdkh fdjhf </TextBlock>
            </TabItem>
            <TabItem Header="Tab 2" Visibility="Hidden">
                <TextBlock>3807689vthvybhgthugbbjgkngoebt4uibn54</TextBlock>
            </TabItem>
        </TabControl>
    </StackPanel>
</Window>

If I just set TabItem's visibility to hidden, the content inside that tab does not hide.

Is there a way to hide tab header and its content together?

Answer

HoboCannibaL picture HoboCannibaL · Feb 19, 2016

You can do that by binding the Visibility to the parent control. If you are using a view model, you can bind the visibility to a property in your view model and use the property for both the TabItem and TextBlock.

<StackPanel>
    <TabControl>
        <TabItem x:Name="tab1" Header="Tab 1" Visibility="Hidden">
            <TextBlock Visibility="{Binding Path=Visibility, ElementName=tab1}">shfsdjkfhksh jkfhd sfjdklh sfjdkh fjdkh fdjhf</TextBlock>
        </TabItem>
    </TabControl>
</StackPanel>