blank_page
Value converts are one of the most important features of the .NET Framework that I use daily. In Silverlight you use value converters to format binded data to your liking. For example, formatting a date to a specific DateFormat (January 1, 2008). Your imagination is the limit when it comes to value converters (think enums, etc).
First let's create our converter. I usually create these classes in a common library to be used everywhere within the solution. Just remember to create a Silverlight Class project if you intend to use these within Silverlight.
1: public class DateTimeConverter : System.Windows.Data.IValueConverter
2: {
3: public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
4: {
5: return (( DateTime )value).ToString("dd MMM, yyyy h:mm:ss tt");
6: }
7: public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
8: {
9: return value;
10: }
11: }
12:
We have a method Convert, which takes several parameters. The value parameter will be the value of the property that we want to convert. It's of type object so we cast it to DateTime and use the ToString method of the DateTime class to format it as we please. Let's now see how to use this convertor in the xaml. First declare the namespace of the converter:
1: <UserControl x:Class="LayoutExperiments.Page"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: xmlns:local=" use Intellisense to choose your namespace ">
The next step is to add the Resource to the UserControl of type DateTimeConverter:
1: <UserControl.Resources>
2: <local:DateTimeConverter x:Key="DateTimeConverter" />
3: </UserControl.Resources>
The last thinig we need to do is configure the binding and add the converter:
1: <TextBlock x:Name="MyText" Text="{Binding SomeDateObject, Converter={StaticResource DateTimeConverter}}"></TextBlock>