#494 – Using a Value Converter to Bind to a Visibility Property
February 14, 2012 4 Comments
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"/> </StackPanel> <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0"> <ComboBox.Items> <ComboBoxItem Content="Visible"/> <ComboBoxItem Content="Collapsed"/> <ComboBoxItem Content="Hidden"/> </ComboBox.Items> </ComboBox>
Code for IValueConverter.Convert:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility visibility = Visibility.Visible; try { if (value != null) { ComboBoxItem item = (ComboBoxItem)value; visibility = (Visibility)Enum.Parse(typeof(Visibility), (string)item.Content, false); } } catch { } return visibility; }
Pingback: Dew Drop – February 14, 2012 (#1,265) ♥ | Alvin Ashcraft's Morning Dew
You can do this … but should you?
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.
Pingback: #495 – Binding to a Visibility Property Without Using a Value Converter « 2,000 Things You Should Know About WPF