Blog

ValueConverters on Silverlight

By David Espino

On several occasions when we want to present screen data on our application, it is necessary to give to it a particular format when it is showed on the screen. The ValueConvertes inside a Silverlight application help us to accomplish this objective. One class of IvalueConverted that is implemented modifies the data that flow to the controls when a Binding is made.

For this example we create a Silverlight application with its own Website.

First, we need a class that is going to help us with our data entity and it’s going to storage the basic data of an order.

publicclassOrder

    {

publicintOrderNumber { get; set; }

publicint Items { get; set; }

publicdouble Total { get; set; }

publicDateTimeDateArrival { get; set; }

    }

 

Inside the main control of the Silverlight Application we need to add some elements that are going to help us to display information from a list of commands.

<UserControl

       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

       xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

       x:Class="ConvertersExample.MainPage"

       Width="640" Height="480">

 

       <Grid x:Name="LayoutRoot" Background="White">

              <sdk:DataGrid Margin="8,52,144,226"AutoGenerateColumns="False">

                     <sdk:DataGrid.Columns>

                           <sdk:DataGridTextColumn Header="Order Number" Binding="{Binding Path=OrderNumber}"/>

<sdk:DataGridTextColumn Header="# of Items" Binding="{Binding Path=Items}"/>

<sdk:DataGridTextColumn Header="Total" Binding="{Binding Path=Total}"/>

<sdk:DataGridTextColumn Header="Date of Arrival" Binding="{Binding Path=DateArrival}"/>

                     </sdk:DataGrid.Columns>

              </sdk:DataGrid>

              <TextBlockHorizontalAlignment="Left"TextWrapping="Wrap" Text="My Orders"VerticalAlignment="Top"FontSize="24"/>

              <Rectangle Fill="#FFF4F4F5" Height="1" Margin="8,35,144,0"StrokeStartLineCap="Flat"StrokeEndLineCap="Flat" Stroke="Black"StrokeThickness="1"StrokeMiterLimit="10"StrokeLineJoin="Miter"VerticalAlignment="Top"/>

       </Grid>

</UserControl>

 

Now it’s necessary that we create a class that implements the IvalueConverter interface that’s going to help us to convert the value displayed on the Date column.

 

publicclassDateConverter: IValueConverter

    {

// This converts the DateTime object to the string to display.

publicobject Convert(object value, TypetargetType, object parameter,

System.Globalization.CultureInfo culture)

        {

 

stringformatString = parameter asstring;

if (!string.IsNullOrEmpty(formatString))

            {

returnstring.Format(culture, formatString, value);

 

            }          

returnvalue.ToString();

        }

 

publicobjectConvertBack(object value, TypetargetType,

object parameter, System.Globalization.CultureInfo culture)

        {

thrownewNotImplementedException();

        }

 

    }

 

 

When the class is created we add the namespace reference to the Xaml created to use the class inside the xaml as a resource.

 

xmlns:local="clr-namespace:ConvertersExample"

 

And we add as a resource the just created class to turn it into dates:

<UserControl.Resources>

<local:DateConverter x:Key="DateConverter" />

</UserControl.Resources>

 

Now we modify our binding on the date column to use this converter and let us throw just the month and the day on screen.

 

<sdk:DataGridTextColumn Header="Date of Arrival" Binding="{Binding Path=DateArrival, Converter={StaticResourceDateConverter},ConverterParameter=\{0:M\}}"/>

 

The completed Xaml after these changes needs to be the following:

 

<UserControl

       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

       xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

       x:Class="ConvertersExample.MainPage"

xmlns:local="clr-namespace:ConvertersExample"

       Width="640" Height="480">

<UserControl.Resources>

<local:DateConverter x:Key="DateConverter" />

</UserControl.Resources>

 

<Grid x:Name="LayoutRoot" Background="White">

<sdk:DataGrid Margin="8,52,144,226"AutoGenerateColumns="False" x:Name="dgOrders">

                     <sdk:DataGrid.Columns>

                           <sdk:DataGridTextColumn Header="Order Number" Binding="{Binding Path=OrderNumber}"/>

<sdk:DataGridTextColumn Header="# of Items" Binding="{Binding Path=Items}"/>

<sdk:DataGridTextColumn Header="Total" Binding="{Binding Path=Total}"/>

<sdk:DataGridTextColumn Header="Date of Arrival" Binding="{Binding Path=DateArrival, Converter={StaticResourceDateConverter},ConverterParameter=\{0:M\}}"/>

                     </sdk:DataGrid.Columns>

              </sdk:DataGrid>

              <TextBlockHorizontalAlignment="Left"TextWrapping="Wrap" Text="My Orders"VerticalAlignment="Top"FontSize="24"/>

              <Rectangle Fill="#FFF4F4F5" Height="1" Margin="8,35,144,0"StrokeStartLineCap="Flat"StrokeEndLineCap="Flat" Stroke="Black"StrokeThickness="1"StrokeMiterLimit="10"StrokeLineJoin="Miter"VerticalAlignment="Top"/>

       </Grid>

</UserControl>

 

In the code behind of user control we add the code to load some fictional orders:

publicpartialclassMainPage : UserControl

       {

              publicMainPage()

              {

                     // Required to initialize variables

                     InitializeComponent();

 

List<Order> orders = CreateOrders();

this.dgOrders.ItemsSource = orders;

 

              }

 

privateList<Order>CreateOrders()

        {

List<Order> result = newList<Order>();

OrderorderObj = newOrder

            {

DateArrival = DateTime.Today.AddDays(2),

                Items = 5,

OrderNumber = 1,

                Total = 20

            };

 

result.Add(orderObj);

 

orderObj = newOrder

            {

DateArrival = DateTime.Today.AddDays(5),

                Items = 10,

OrderNumber = 2,

                Total = 100

            };

 

result.Add(orderObj);

 

 

orderObj = newOrder

            {

DateArrival = DateTime.Today.AddDays(10),

                Items = 2,

OrderNumber = 3,

                Total = 50

            };

 

result.Add(orderObj);

 

return result;

        }

       }

 

Once we have done this, we hit F5 to run our application and review how the converter gives the date only with the name of the month and day.

1

 

Comments

Leave a comment

 
 
 
 
CAPTCHA Image Validation