#494 – Using a Value Converter to Bind to a Visibility Property

You can bind the Visibility property of a control to a data item whose type is System.Windows.Visibility.  You can also bind to an item whose type is string, provided that the string values returned represent one of the enumerated values from the Visibility type.

The example below shows how to use a value converter to convert from the SelectedValue of a ComboBox (a ComboBoxItem) to the Visibility type.

        <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, Converter={StaticResource cboVisibilityConverter}}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>

Code for IValueConverter.Convert:

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            Visibility visibility = Visibility.Visible;

                if (value != null)
                    ComboBoxItem item = (ComboBoxItem)value;
                    visibility = (Visibility)Enum.Parse(typeof(Visibility), (string)item.Content, false);
            catch { }

            return visibility;

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

4 Responses to #494 – Using a Value Converter to Bind to a Visibility Property

  1. Pingback: Dew Drop – February 14, 2012 (#1,265) ♥ | Alvin Ashcraft's Morning Dew

  2. James Ashley says:

    You can do this … but should you?

    • Sean says:

      Stay tuned–in the pipe for tomorrow is a post about leveraging the fact that the Visibility dependency property can do its own conversion from a string. Still important to know about value conversion.

  3. Pingback: #495 – Binding to a Visibility Property Without Using a Value Converter « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: