xaml Converters Converters 101


Example

XAML controls may have dependency properties that can be bound to objects from DataContext or other controls. When the type of the object being bound is different from the type of the target DependencyProperty, a converter may be used to adapt one type to another.

Converters are classes implementing System.Windows.Data.IValueConverter or System.Windows.Data.IMultiValueConverter; WPF implements some out of the box converters, but developers may see use in custom implementations, as it is frequently the case.

To use a converter in XAML, an instance can be instantiated in the Resources section. For the example below, System.Windows.Controls.BooleanToVisibilityConverter will be used:

<UserControl.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</UserControl.Resources>

Notice the x:Key element defined, which is then used to reference the instance of BooleanToVisibilityConverter in the binding:

<TextBlock Text="This will be hidden if property 'IsVisible' is true"
           Visibility="{Binding IsVisible, 
                                Converter={StaticResource BooleanToVisibilityConverter}}"/>

In the example above, a boolean IsVisible property is converted to a value of the System.Windows.Visibility enumeration; Visibility.Visible if true, or Visibility.Collapsed otherwise.