Silverlight 4 Data Binding: String Format

This is the second substantial coding post to reach my goal of three by the end of the year. In this post I will demonstrate the new string formatting functionality in Silverlight 4 data binding. There have been a lot of new functionality in data binding. The string formatting functionality will help save time and reduce code. These enhancements help make business applications quicker and easier to program in Silverlight.

The first thing I noticed in Silverlight 4 is that you now have Intellisense support for binding.

Prior to Silverlight 4 you had to manually type binding statements. This was prone to “fat finger” errors, mistyping a key word or forgetting to close brackets. True, there were GUI means of binding (through Expression Blend) that could help prevent these errors but now there is support right in the XMAL editor. This should help increase productivity and reduce errors.

Now to the main task at hand, formatting strings. Many business objects have properties that represent dates, currencies and the like. In Silverlight 3 you had two options when it came to controlling the format of these properties when data binding. First you could add a property to your view model that returned the properly formatted string. This is not ideal because to have maintain extra properties that would hand conversion to and from the desired format.

The second choice you had was to create a value converter. This method off loaded the conversion code to a different class keeping your view model clean. This also allows you to reuse the code. For instance if all dates need to be displayed in specific format they could use the same value converter.

To create a value converter you first create a class that implements the IValueConverter interface:

   1: public class CurrenceyValueConverter : IValueConverter

This interface requires the implementation of two methods: Convert and ConvertBack. These methods contains the code to convert to and back from the desired format.

Here is and example of the Convert method for converting double values to currency:

   1: public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   2: {

   3:    string retVal = string.Empty;


   5:    double? cost = value as double?;


   7:    if (cost != null)

   8:    {

   9:        retVal = cost.Value.ToString("C", 


  10:    }


  12:        return retVal;

  13:    }

Now in XAML you add a resource for your value converter:

   1: <Grid.Resources>

   2:     <local:CurrenceyValueConverter x:Key="CostConverter" />

   3: </Grid.Resources>

Finally, you reference the resource in the binding:

   1: <TextBlock Text="{Binding Path=Cost, Converter={StaticResource 

CostConverter}}" Margin="10" />

This seems like a lot of work just, not to mention and class file to get a dollar sign in front of a double value. Silverlight 4 makes this process a whole lot easier.  In Visual Studio 2010 all you have to do is select the control you are binding to, select the property and launch the binding window. Under the options tab you now have the ability to control the format for the text.

When you select a format the following code gets generated:

   1: <TextBlock  Margin="10" Text="{Binding Path=Cost, StringFormat=\{0:c\}}" />

Combine this functionality with the Intellisense and you should be able to increase your productivity, produce cleaner code, and build business applications faster.  Does this mean that you will no longer need to write value converters, no they are still useful. For instance if you actually need to convert the cost to a specific currency (Dollars to Euros), you will need a converter. It does mean that you no longer need to write converters to format text. There are a many other new data binding features introduced in Silverlight 4. I hope to address some of them in future posts.

This entry was posted in .NET, C#, Silverlight. Bookmark the permalink.

4 Responses to Silverlight 4 Data Binding: String Format

  1. Rob Siklos says:

    The last half of this article does not render properly.

  2. Hi there would you mind sharing which blog platform you’re working with? I’m planning to start my own blog in the near future but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something
    completely unique. P.S Sorry for getting off-topic but I had
    to ask!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s