Silverlight 4 Binding and StringFormat in XAML

I discovered this amazing feature almost by accident and it has made this one part of my design so much easier that I had to share it.

A new feature in Silverlight 4 is the ability to using the StringFormat feature when binding. Previously, if I wanted to have a piece of text that said “Your name is [username]” I could either use the old Horizontal-Stack-Panel-And-2-TextBlocks trick (as seen below)…
<StackPanel Orientation=”Horizontal”>
<TextBlock Text=”Your name is” Margin=”0,0,4,0″/>
<TextBlock Text=”{Binding username}“/>

</StackPanel>

…or write a value converter (not going to be seen below because there’s a great example of it over here. Incidentally, that example is totally irrelevant if you’re going to use StringFormat, but more on that in a second).

The StringFormat option in Silverlight 4 allows you put all that information into a single field, which is extremely useful not only for TextBlocks, but for Content fields in a Button. In fact, let’s use that as an example.

Let’s say you want to create a Button to log out, so you want it to say “Log Out of <Username> Account”. (A bit clumsy, but the technique is the important part.) All you would have to do is the following:

<Button Content=”{Binding username, StringFormat=’Log Out of {0} Account’}“/>

This gets even better for things like number formatting. Let’s say we want the user to enter an amount of money (for example, $1,593.29) into a TextBox (maybe in a PayPal application). If we have bound that value to a numeric format, we can express that format through binding and when the TextBox loses focus, the StringFormat will take the number entered and format in a currency format.

<TextBox Text=”{Binding paymentAmount, StringFormat={0:C2}}/>

The only issue with numerical and date formats is they the MUST be bound to a number or date.

With that in mind, here is a sampling of StringFormat options, stolen mostly from Kathy Kam. For more complete options, check out the MSDN articles on String.Format and trial-and-error your way through things. If you want to play around with this, download my StringFormat project or look at the Silverlight sample app at the bottom of this page.

Strings

For a string with the value “Silverlight”

Using {0,#} effectively forces the string to be at least # characters long, using spaces to pad it to the requested length.

StringFormat={0,20} : “                  Silverlight”
StringFormat={0,-20} : “Silverlight                  ”
StringFormat=’I just typed &quot;{0}&quot;.’ : “I just typed “Silverlight”.”

MSDN article on Composite Formatting

Numbers

For a double with the value : “38293.53”

StringFormat=c : “$38,293.53” – Use ‘c’ for currency
StringFormat=e : “3.829353e+004” – Use ‘e’ for exponential (scientific)
StringFormat=n : “38,293.53” – Use n for number

You can also use these in the following format:

{0:(letter)(number)}

where (number) indicates how many decimal places there should be. The format will use standard rounding rules to determine the last digit. For example:

StringFormat={0:c0} : “$38,294”
StringFormat={0:n4} : “38,293.5300”
StringFormat=You have {0:c1} : “You have $38,293.5”

MSDN article for standard number formatting
MSDN article for custom number formatting

Dates

The date formatting has a huge range of options.

For the DateTime of “April 17, 2004, 1:52:45 PM”

You can either use a set of standard formats (standard formats)…
StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”

… or you can create your own date formatting using letters (custom formats)

StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”

MDSN article for standard date formatting
MSDN article for custom date formatting

Sample App

38 thoughts on “Silverlight 4 Binding and StringFormat in XAML

  1. You can certainly see your expertise within the article you write.
    The sector hopes for even more passionate writers like you who are not
    afraid to say how they believe. Always follow your heart.

  2. Hi can you please tell me if we can use StringFormat options in XAML, to represent a string in our own format. For example a six digit number is displayed as (000)-(000)

  3. There are other products on the market today that are in competition with Silverlight and can create similar effects, such as Adobe ® ® ® Flash and JavaFX. So why would a developer choose to use Silverlight in other products? The answer is simple: you must use the product that caters to their environment and best suits your requirements for design and development. The list of features included in Silverlight is exhaustive and there are many published articles that cover Silverlight comparison with other products.

    http://www.techyv.com/article/what-silverlight-and-why-do-we-need-it

  4. I tried this technique but it does not work:

    I think we need to use TextBock to trigger the StringFomat.

    Here is my problem, I want to add a world “Do” in front of the value of my GetAction property and I dont want to do this with converter class Do you have any ideal how to do this with string format?
    CommandParameter=”Do{Binding GetAction}”

    Thanks,

    Jdang

  5. Guys,

    Can anybody say how to show a negative sign for a negative currency value. Right the the negative value is shown in the brackets.

    Eg: (123.45). But I want to show as -123.45

    Thanks!

  6. How to get custom strings from resource file?
    for eg:

    I have to get this “‘Your name is ” string from resource file….

  7. How can I change the currency symbol to £ instead of $.
    My PC’s Regional setting are set to UK but still showing $ as currency symbol

  8. Another thing you can do is specify different formatting for positive, negative and zero value numbers. For example, if you want to always have a positive or negative sign in front of your value, you would use the following {Binding Path=MyNumber, StringFormat=’+##;-##;0′}

  9. Thanks for sharing! I can get rid of tons of DataConverters on my code just by using this.

Comments are closed.