viernes, agosto 01, 2008

Value Converters - Default Value Converter

This is the second of several posts related to Value Converters. Reading the posts in order can be useful, but not necessary. As we saw yesterday sometimes we need to specify a DefaultValue for cases where there's no value specified by our datasource. This is a look of the application with data, then without a phone number and the third pic shows how would it look with the DefaultValueConverter.

With data:

Without data:
Wit DefaultValueConverter:
The change in XAML is really simple, this is the original line:
<TextBlock Text='{Binding Mode=OneWay, Path=PhoneNumber}'/>
This is the modified line:

<TextBlock Text='{Binding Mode=OneWay, Path=PhoneNumber, ConverterParameter="[Not Available]", Converter={StaticResource DefaultValueConverter}}'/>

We also need to add a Resource that holds the reference to our DefaultValueConverter

<SilverlightApplication14:DefaultValueConverter x:Key="DefaultValueConverter"/>

We added two attributes to the Binding object, a ConverterParameter and a resource that will hold an instance of our ValueConverter. A ValueConverter is simply a class that implements IValueConverter and consists of two methods Convert and ConvertBack. ConvertBack is used with TwoWay BindingMode, but we won't use it here. The Convert method simply checks if the value is null and if it is, it returns the parameter which will hold the object specified in the ConverterParameter.

public class DefaultValueConverter : IValueConverter
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
if (value == null)
return parameter;
return value;
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
throw new NotImplementedException();

In WPF the Binding object has a DefaultValue property, so there's no need to create a ValueConverter there.

You can download the attached code here
I format my code using Manoli's website
Don't forget to vote for your favorite topics for this column.

No hay comentarios.: