#495 – Binding to a Visibility Property Without Using a Value Converter

You can use a value converter to convert a string value to a value of type System.Windows.Visibility, allowing data binding to a Visibility property.  You can also just set a Visibility property directly to a string, avoiding the need for a value converter.

In the example below, we bind to the Content property of a ComboBoxItem, which we access through the SelectedValue property of a ComboBox.  Since Content contains a string, the binding to Visibility works without a conversion.

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Snoopy" Margin="3" Background="BurlyWood"/>
            <Label Content="Waldo" Margin="3" Background="Thistle"
                   Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue.Content}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        </StackPanel>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
            <ComboBox.Items>
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>
            </ComboBox.Items>
        </ComboBox>
        <Label Content="Select visibility of middle Label" HorizontalAlignment="Center"/>
    </StackPanel>

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #495 – Binding to a Visibility Property Without Using a Value Converter

  1. Pingback: Dew Drop – February 15, 2012 (#1,266) | Alvin Ashcraft's Morning Dew

Leave a comment