WPF - Passing string to ConverterParameter
There are enough online sources that talk about how to buid and use custom Converters in WPF and also how to pass parameters to these converters. However for some reason, all these examples tend to either use a single integer or a single word string. So recently when I had a need for passing a sentence as parameter, I was confused.
Fortunately the simple trick of using single quotes inside of double quotes to provide strings worked in this case as well. Following are two ways you can pass a string that has multiple words to a converter.
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, Converter={StaticResource custConverter}, ConverterParameter='The time of the day is '}" />
Though VS color coding goes for a toss, the designer still loads fine and code also runs fine. If you use the more elaborate syntax for setting the binding, the regular double quotes will also work.
<TextBlock>
<TextBlock.Text>
<Binding Source="{x:Static sys:DateTime.Now}" Converter="{StaticResource custConverter}" ConverterParameter="The time of the day is " />
</TextBlock.Text>
</TextBlock>
And the converter logic in this case is pretty trivial and is as below.
public class DateConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime dt = (DateTime)value;
return parameter.ToString() + dt.ToLongDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
BTW, needless to say that you need to include the appropriate namespace for the DateTime.Now to work and that will be xmlns:sys="clr-namespace:System;assembly=mscorlib"
[Updated: April 25, 2008] There is another simple way to pass strings. First define a resource as below
<sys:String x:Key="mystring">The time of the day is </sys:String>
And now use this resource for setting the value of ConverterParameter as below
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, Converter={StaticResource custConverter}, ConverterParameter={StaticResource mystring}}" />
