TabControl: all TabItems collapsed, but content of 1st TabItem still visible

余生颓废 提交于 2019-12-03 16:15:50
Sheridan

Ok, so you've found a real problem here... I looked around online and found several posts that relate to this. Some say that this is a bug, while others say that it is the designed behaviour. don't know which, although it certainly seems to be more of a bug than a feature.

Either way, you want to know how to deal with the problem. .. there are several solutions. One is just to set the TabItem.Content to null whenever you want to hide the tab and another is another involves adding an empty TabItem and selecting that item before hiding (so that it's empty content is shown).

You can attach a handler to the TabItem.IsVisibleChanged Event to be notified when the Visibility property has been changed:

public void TabItemIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Hide TabItem.Content here
}

Here are some links to the relevant posts:

Bug in TabControl/TabItem`s content visibility?
WPF TabControl - Select different tab when TabItem Visibility changes
Is there a workaround for this tabcontrol/tabitem bug

Another solution that I prefer over the ones suggested: Bind the visibility of the TabItem and its content to the same property (using the BooleanToVisibilityConverter). Here's a simple example:

<UserControl.Resources >
    <BooleanToVisibilityConverter x:Key="boolToVis"/>
</UserControl.Resources>
<Grid>
    <TabControl>
        <TabItem Header="TabItem 1" Visibility="{Binding Item1Visibility, Converter={StaticResource boolToVis}}">
            <Label Content="Content 1" Visibility="{Binding Item1Visibility, Converter={StaticResource boolToVis}}"/>
        </TabItem>
        <TabItem Header="TabItem 2" Visibility="{Binding Item1Visibility, Converter={StaticResource boolToVis}}">
            <Label Content="Content 2" Visibility="{Binding Item1Visibility, Converter={StaticResource boolToVis}}"/>
        </TabItem>
    </TabControl>
</Grid>

Could be a WPF bug, anyway bypass by binding the content visibility to the tab item visibility.

    <TabControl>
        <TabItem x:Name="_test1Tab" Header="Test 1" Visibility="Hidden">
            <Label Visibility="{Binding ElementName=_test1Tab, Path=Visibility}">Test1</Label>
        </TabItem>

        <TabItem x:Name="_test2Tab" Header="Test 2" Visibility="Hidden">
            <Label Visibility="{Binding ElementName=_test1Tab, Path=Visibility}">Test2</Label>
        </TabItem>
    </TabControl>

My solution to this was to put the TabItem I wanted to hide in another position. The problem happens only if you want to collapse only the first TabItem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!