New to Silverlight 4 is the ability to format bound data using the StringFormat
property that we all know and love from .NET. Using the StringFormat
property when doing data binding is perfect for when you wish to format the value that returns from the bind in a specific way, such as currency or any numerical format. Using StringFormat
is pretty straightforward; just add the StringFormat
property after the binding declaration, just like you did with the mode earlier:
<TextBlock Text="{Binding Price, StringFormat=c}"/>
The preceding line of code will format the Price
property to a currency, which on my machine translates to 5.00$. But why did it choose the dollar symbol and not any other currency symbol? The reason for that is that formatting picks up on the default culture of the system. As my default culture is en-US, I get the dollar symbol. If I had my culture set as he-IL, I would have got the New Israeli Shekel (NIS) symbol.
Currency is just one example of use for StringFormat
, of course. Another example for this feature can be formatting strings. Let's say we wish to have a dynamic label, for example, "Your teacher expects to receive X apples today!", where X is a random number between 1-10. Instead of using three separate TextBlock
elements (one for the text until the random number, the second for binding the random number, and the last one for the rest of the phrase), we can use a single TextBlock
element as follows:
<TextBlock Text="{Binding RandomNumber, StringFormat='Your teacher expects to receive {0} apples today!'}"/>
There are many usages for StringFormat
and when building an LOB application using Silverlight, you will find yourself using this feature for a fair amount of time.
For a list of options and usages of StringFormat
, visit Matthias Shapiro's great post in his blog at http://www.designersilverlight.com/2010/05/28/silverlight-4-binding-and-stringformat-in-xaml/.
3.142.199.181