Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Control TabItem visibility from a checkbox

I looked at: Visibility Binding using DependencyProperty

and 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

I have some tabs I want to control their visibility from a checkbox i.e.

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

Ideally I would do

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

         </TabItem>

or some such but that is not correct syntax. What is easiest/correct syntax?

like image 677
Charles Mark Carroll Avatar asked Aug 09 '11 03:08

Charles Mark Carroll


1 Answers

You can use the built-in BooleanToVisibilityConverter. Here's a working sample:

<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>
like image 132
Matt Hamilton Avatar answered Nov 20 '22 17:11

Matt Hamilton