WPF控制TabItem来自复选框的可见性

时间:2011-08-09 03:07:01

标签: wpf wpf-controls binding

我看了看: Visibility Binding using DependencyProperty

http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx http://www.vistax64.com/avalon/240-no-checkbox-checkedchanged.html http://geekswithblogs.net/thibbard/archive/2007/12/10/wpf---showhide-element-based-on-checkbox.checked.aspx

我有一些标签我希望通过复选框控制其可见性 即。

        <TabItem Header="Preferences" Name="tabItem4"></TabItem>

理想情况下我会这样做

        <TabItem Header="Preferences" Name="tabItem4">
                <DataTrigger Binding="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True">
                    <Setter Property="Visibility" Value="True" />
                </DataTrigger>

         </TabItem>

或其他一些但是语法不正确。什么是最简单/正确的语法?

1 个答案:

答案 0 :(得分:36)

您可以使用内置BooleanToVisibilityConverter。这是一个工作样本:

<Window x:Class="WpfApplication16.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:my="clr-namespace:WpfApplication16"
            Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="b2v" />
    </Window.Resources>

    <StackPanel>
        <CheckBox x:Name="chk" Content="Show There" />
        <TabControl>
            <TabItem Header="Hello" />
            <TabItem Header="There" Visibility="{Binding IsChecked,ElementName=chk,Converter={StaticResource b2v}}" />
            <TabItem Header="World" />
        </TabControl>
    </StackPanel>
</Window>