hardywang
hardywang

Reputation: 5192

Dynamically hide a WPF TabItem

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?

Upvotes: 3

Views: 12507

Answers (2)

Guttsy
Guttsy

Reputation: 2119

If you set Visibility to Hidden for the selected/active tab, you'll need to select a different tab, e.g.

<StackPanel>
    <TabControl>
        <TabItem x:Name="T1" Header="Tab 1" Visibility="Hidden" >
            <TextBlock>1111111111111111111</TextBlock>
        </TabItem>
        <TabItem x:Name="T2" Header="Tab 2" IsSelected="True">
            <TextBlock>22222222222222222222222</TextBlock>
        </TabItem>
    </TabControl>
</StackPanel>

You do not need to hide the content of the TabItem provided that the TabItem is hidden and unselected.

Upvotes: 1

HoboCannibaL
HoboCannibaL

Reputation: 191

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>

Upvotes: 3

Related Questions