Data Conversion with Silverlight 3

In this conclusion to a five-part series on data binding with Silverlight 3 we will discuss data conversion. As with the other parts, we'll explain when and why you need to convert data, and go through a step-by-step process to show you how it's done.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
June 01, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Images referenced in this article can be viewed in two files available for download, SL3Data.rar and SL3Validate.rar.

Data Conversion

In a common binding, the information passed from the source to the target needs no change. This seems logical, but it's not always the situation you're dealing with. Say, for instance, that the data is stored in some format, while what you hope to display is in another format. In this case, you need to perform data conversion. The following list shows some typical cases for data conversion:

  • Data stored as an RGBA color value, but you want to display it in its related color name.
  • Data stored as a floating point number, but you want to display it in the cultural currency form.
  • Data stored as a date in a DateTime form, but you hope to display it in a calendar control.
  • Creating a specific type of Silverlight object.  For example, you can read a block of binary data and create a BitmapImage object that can be bound to an Image element.

To convert the data, a converter must be used in data binding, concretely as follows:

First, create a class that implements the IValueConverter interface, which acts as a converter.

Then, implement the Convert and possible ConvertBack methods of the IValueConverter interface. The Convert method is responsible for converting the required source data into a format and then transferring it to the target control, so that the data format appears as expected in the control. The ConvertBack method is the inverse implementation of the Convert method.

The following indicates the description for the Convert method:  

 

Object Convert(

    Object value,

    Type targetType,

    Object parameter,

    CultureInfo culture

 

 

The parameters are explained below:

  • value, whose type is System.Object representing the value that is produced by the binding target.
  • targetType, whose type is System.Type representing the type to convert to.
  • parameter, whose type is System.Object representing the converter parameter to use.
  • culture, whose type is System.Globalization.CultureInfo representing the culture to use in the converter.

Define your converter

Using the converter is a piece of cake. Just follow the steps listed below:

1. Inside your XAML file, define your converter as a resource and assign it a name using the x:Name property:  

 

<UserControl.Resources>

  <local:DateFormatter x:Key="engFormatConverter" />

</UserControl.Resources> 

 

2. Inside the targeting control, when you perform the data binding, refer to the converter using the following format:  

 

Converter={StaticResource engFormatConverter}  

 

That's it.  Next, let's take a look at a concrete example.

Converting the data

Figure 4 below gives one of the running time snapshots.  Note the date format shown in the ComboBox control at the top area. To do this, we've utilized a custom converter converting the date of the source object into specified format, and then show it in the ComboBox control.  For details, go on reading.

Figure 4-data conversion illustration (corresponding to the file DataBindingDemo05.xaml)  

First, we have to create a DateFormatter class that implements the IValueConverter interface.  Here's the related code (inside file DateFormatter.cs):

public class DateFormatter : IValueConverter

{

    public object Convert(

        object value,

        Type targetType,

        object parameter,

        System.Globalization.CultureInfo culture)

    {

        string formatString = parameter as string;

        if (!string.IsNullOrEmpty(formatString))

        {

            return string.Format(culture, formatString, value);

        }

        return value.ToString();

    }

    public object ConvertBack(object value, Type targetType,

        object parameter, System.Globalization.CultureInfo culture)

    {

        throw new NotImplementedException();

    }

} 

 

Obviously, we've only customized the Convert method, converting the DateTime object into the required format using the passed formatted string and the culture parameter. If the passed formatted string is null or empty, we only need to convert it into a string and return it.

Moreover, you should notice that in the one way binding, you don't need to customize the ConvertBack method; even doing that, nothing will happen.

XAML code implementation

 

Now, let's check out the related implementation in the XAML code in the sample application: 

<UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

    x:Class="SL3DataBindingTest.DataBindingDemo05"

        <!-......(elided to save space) -->

    xmlns:local="clr-namespace:SL3DataBindingTest"             

    Width="727.25" Height="620.25">

    <UserControl.Resources>

        <local:DateFormatter x:Key="engFormatConverter" />

    <!-......(elided to save space) -->

    </UserControl.Resources>

    <Border Background="#FFFFFFFF">

    <!-......(elided to save space) -->

                <ComboBox x:Name="cboBook" Cursor="Hand"

                         ItemsSource="{Binding Mode=OneWay}"

                         FontSize="16"

                         Margin="5,114,5,0"

                         VerticalAlignment="Top" Height="90"

                         ScrollViewer.VerticalScrollBarVisibility="Visible"

                         ScrollViewer.HorizontalScrollBarVisibility="Visible" Background="#FF00FF69" >

                  <ComboBox.BorderBrush>

                     <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

    <!-......(elided to save space) -->

                  </ComboBox.BorderBrush>

                    <ComboBox.ItemTemplate>

                        <DataTemplate>

                            <StackPanel Orientation="Horizontal" >

                                <TextBlock Text="{Binding Mode=OneWay, Path=PublishDate,

                                           Converter={StaticResource engFormatConverter},

                                           ConverterParameter={0:yyyy-MMM-dd-dddd},

                                           ConverterCulture=en-US}"

                                   Margin="0,0,10,0" />

    <!-......(elided to save space) -->

    </Border>

</UserControl>

Please notice the contents of the two properties-ConverterParameter and ConverterCulture. Then, you can follow this in your own custom format.

Since the data in this sample is constructed on the client side and simple, we will not dwell upon them.

Summary

In this series, we've explored nearly all the details related to Silverlight 3 data binding with concrete samples, from simple one way binding to collection data binding to validation and conversion. At the same time, you may have drawn an important conclusion, i.e. the client-side validation support of Silverlight 3 is still in its infancy. Finally, I recommend interested readers to continue to dig into the newest server-side WCF Ria Services (in support of VS2008 and VS2010), which provides a better server-side validation solution.

blog comments powered by Disqus
SILVERLIGHT ARTICLES

- With Silverlight Gone, Whither SharePoint?
- Silverlight in the News
- Silverlight Has a Bright Future
- Windows 8 Effects on .Net and Silverlight De...
- Microsoft`s SkyDrive Abandons Silverlight
- Silverlight Developers Unhappy with Windows ...
- Best Silverlight Examples
- How to install Silverlight for Windows Phone
- Microsoft Reveals Silverlight 5 Features
- Silverlight News: SRS and Microsoft to Bring...
- Silverlight 4.0: Paging Through Data using D...
- Silverlight 4.0: Navigating Data Using Domai...
- Silverlight 4.0: Filtering Data Using Domain...
- Silverlight 4.0: Sorting and Grouping Data w...
- Silverlight 4.0: Query Parameters of DomainD...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials