Using a ConverterParameter in a Silverlight 2 Value Converter
In building a Silverlight 2 application with data binding, you often need to convert between data types and many of the data types that you use already have built-in converter. One type that does have a built-in converter is the DateTime type. what this means is that when a binding to a date field, like with a SyndicationItem.PublishDate.Date, you don't have to specify how the value gets converted. Often that isn't optimal. Emil Stoychev wrote a great article on how to write a custom DateTime converter for birthdays, but I wanted to make a more generic DateTime converter class. To do this, I used the ConverterParameter part of the Data binding syntax:
<TextBlock Text="{Binding PublishDate.Date, Converter={StaticResource DateTimeConverter},
ConverterParameter=d}"/>
In doing this I am passing a ConverterParameter, "d", to the Convert() function as the parameter parameter. This enables me to specify the formatting in the XAML. In this case the 'd' format will make a date like 7/30/2008 - without the time:
using System;
using System.Windows.Data;
namespace Journalist2
{
/// <summary>
/// DateTime value converter
/// </summary>
public class DateTimeConverter : IValueConverter
{
#region IValueConverter Members
/// <summary>
/// Convert from a DateTime to a string
/// </summary>
/// <param name="value">a DateTime</param>
/// <param name="targetType">a string type</param>
/// <param name="parameter">the formatting parameter for DateTime.ToString()</param>
/// <param name="culture">the culture to use</param>
/// <returns>a string</returns>
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is DateTime)
{
var dt = (DateTime) value;
if (parameter == null)
{
return dt.ToString(culture);
}
else
{
return dt.ToString(parameter as string, culture);
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var strValue = value as string;
if (strValue != null)
{
return DateTime.Parse(strValue, culture);
}
return null;
}
#endregion
}
}