WPF and Silverlight use Binding objects to connect data values to UI properties. For example, to display the name of a customer in a TextBlock element, you could use this XAML:
XAML |
Copy Code
|
---|---|
<TextBlock Text="{BindingFirstName}" /> |
In this example, the Text property of the TextBlock will be automatically synchronized with the content of the FirstName property of the data object currently assigned to the DataContext property of the TextBox element or any of its ancestors.
The Binding class is convenient but not very flexible. For example, if you wanted to bind the TextBlock above to the customer’s full name, or to make the text red when the customer account is negative, you would need a Converter.
The Converter parameter of the Binding object allows you to add arbitrary logic to the binding, converting values when they are transferred between the source and the target.
To illustrate, and still using the example above, imagine we wanted the TextBlock to show the customer’s full name, and to display the text in red when the customer’s account is negative. To accomplish this, we would need two converters, implemented as follows:
XAML |
Copy Code
|
---|---|
/// <summary> /// Converter for Foreground property: returns a red brush if the /// customer amount is negative, black otherwise. /// </summary> publicclass ForegroundConverter : System.Windows.Data.IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var c = value as Customer; return c.Amount < 0 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// Converter for customer's full name: returns a string containing /// the customer's full name. /// </summary> publicclass FullNameConverter : System.Windows.Data.IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var c = value as Customer; return string.Format("{0} {1}", c.FirstName, c.LastName); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } |
Once the converters have been defined, they can be used in XAML as follows:
XAML |
Copy Code
|
---|---|
<Grid> <Grid.Resources> <local:FullNameConverterx:Key="_cvtFullName" /> <local:ForegroundConverterx:Key="_cvtForeground" /> </Grid.Resources> <TextBlock Text="{BindingConverter={StaticResource _cvtFullName}}" Foreground="{BindingConverter={StaticResource _cvtForeground}}" /> </Grid> |
This solution works fine, but there are a few shortcomings: