Saturday, August 28, 2010

WPF - Using Converter and StringFormat together for same Binding

We are so used to using Converters. Sometimes it is easier to use StringFormat then defining a converter (the whole class implementing IValueConverter or IMultiConverter. The unexpected happen when we use them together. Well it should not be unexpected because it is well documented. When we use StringFormat together with Converter then Converter is applied first then StringFormat is applied on the bound data.

http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.stringformat.aspx

For example, if we apply like this:
<TextBlock Text="{Binding Path=CurrentDate, StringFormat='\{0:MMMM\}', Converter={StaticResource DefaultLowerCaseConverter}}"/>

It would be better if we format within the Converter. In this example, we are converting a date to string in a particular format. We are then formatting the string to lower case.

class DefaultLowerCaseConverter: System.Windows.Data.IValueConverter
{

#region IValueConverter Members

public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return ((DateTime) value).ToString("MMMM").ToLower();
}

public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}

#endregion
}

We can use this converter like this:
<TextBlock Text="{Binding Path=CurrentDate, Converter={StaticResource DefaultLowerCaseConverter}}"/> 

No comments: