Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

New Data Binding Features in Silverlight 4

Posted by Viral Sarvaiya on October 11, 2010

Data Binding and String Formatting

In prior versions of Silverlight, in order to perform string formatting while data binding you would need to write a converter that would format the data during binding. In Silverlight 4 you are now able to format the data directly in XAML. This greatly simplifies the process of creating bindings that require some formatting of the data. Adding string formatting is as simple as adding a StringFormat extension in the XAML markup of the data binding. The StringFormat extension supports the same formatting options as the String’s Format method. Consider the following XAML. There are four text boxes displayed, all bound to the same property in code behind. The difference, however, is that each TextBox change displays the data differently based on the binding’s StringFormat extension. The first TextBox shows the raw data, the second formats the data to three decimal places, the third show the value in scientific notation, and the fourth shows the data as currency.

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


<RowDefinition Height="*" />

<RowDefinition Height="*" />

<RowDefinition Height="*" />

<RowDefinition Height="*" />





Text="{Binding DecimalValue}" />




Text="{Binding DecimalValue, StringFormat='##.###'}" />




Text="{Binding DateValue, StringFormat='MMM dd, yyyy'}" />




Text="{Binding DecimalValue, StringFormat='c'}" />


As you can see from this example, you can easily change the format of data directly through the XAML.

TargetNullValue and FallBackValue Extensions

Two other extensions have been added to the base binding class in Silverlight 4: the TargetNullValue and FallBackValue extensions. These extensions allow you to specify data that will be displayed in the case when the data being bound to the control is not as expected. TargetNullValue provides a value for the binding that should be used if the data value being bound is null. An example of using this extension is shown here:

<TextBox Text="{Binding ValueName, TargetNullValue='Value is Null'}" />

FallBackValue provides a value to be used if the bound data is missing or if there was a mismatch that occurred. An example of using the FallBackValue extension is shown here:

<TextBox Text="{Binding ValueName, FallbackValue='Value Not Found'}" />

Thanks you.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: