8

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?

Community
  • 1
  • 1

1 Answers1

43

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>
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • 1
    I found a very useful related solution, that allows for inverse visibility binding (i.e. hidden when checked): http://stackoverflow.com/a/5182660/538403 – Mark Adamson Aug 14 '14 at 12:39
  • 1
    I am trying to use your proposal on a datagridtextcolumn but I just get the following error: > System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=IsChecked; DataItem=null; target element is 'DataGridTextColumn' (HashCode=44515427); target property is 'Visibility' (type 'Visibility') – Erik Thysell Mar 28 '18 at 03:32
  • 1
    @MarkAdamson EXCELLENT example - my upvote. Thank you for sharing your knowledge - it saved me many hours (after I had already spent some). Moreover, it shows the power of the [BooleanToVisibilityConverter Class](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.booleantovisibilityconverter?view=netcore-3.1) that many readers (like myself) of your response can benefit from. – nam Nov 01 '20 at 16:29