Matthias Shapiro

developer/integrator with IdentityMine, infovis enthusiast

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

This entry was posted in Silverlight 4, XAML and tagged , , , . Bookmark the permalink.

34 Responses to Silverlight 4 Binding and StringFormat in XAML

  1. Cool tip man !!!!!!!! Thanks for sharing !!!!

  2. Karlkim SK

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

  3. Pingback: Markus Tamm » Blog Archive » Links 31.05.2010

  4. Pingback: Dew Drop – May 31, 2010 | Alvin Ashcraft's Morning Dew

  5. Pingback: Dew Drop – May 31, 2010 | Alvin Ashcraft's Morning Dew

  6. Very well done article. The Silverlight app at the bottom is very impressive. I’m sure that took some effort. It is appreciated.

  7. Diggin’ this. Totally great way to bind with formatting.

  8. Thanks for the tip. This is a great feature that I had no idea about.

  9. Thank you wery much! Great post!

  10. 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′}

  11. Anyone know how I can show a Currency format with 2 decimal places, ONLY if there are decimals? e.g.
    25 should show as $25 and 25.01 should show as $25.01
    http://stackoverflow.com/questions/3219116/string-format-expression-to-show-currency-with-2-decimal-places-only-if-there-are

  12. Jhelumi

    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

  13. Pingback: Using Silverlight 4 StringFormat for Data Binding a TextBlock to a Slider with no decimals showing « ADdendum

  14. You write Good articles,keep up good work.

  15. Sridhar

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

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

  16. Deepak

    Hey ,,, Many thanks… was looking for that!!! Thumbs Up!!! ;)

  17. Francis

    Great help for when a dataconverter is overkill. Thanks!

  18. Pingback: Dar formato de moneda a TextBox « hefesoft

  19. Pingback: A classic memory game: Part 2 – The game logic, connecting the ViewModel and the View | www.nalli.net

  20. Pingback: A classic memory game: Part 2 - The game logic, connecting the ViewModel and the View

  21. Pingback: Data Binding and StringFormat in Silverlight « Matt Duffield

  22. Satya

    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!

  23. Jdang

    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

  24. Alek

    Cool stuff man, very helpful. every time when i need this info I find it here

  25. stevenmarkgil

    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

  26. Tried to run the above binding example and now i can’t connect to my asp development server… aargh….

  27. Anil

    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)

  28. Hi there!! Is there a chance you could let me translate and use your exercise in Spanish?

  29. Pingback: Complete Guide to Windows Phone StringFormat Binding - Appsmash - Site Home - MSDN Blogs

  30. 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.

  31. Hi there everyone, it’s my first pay a visit at this site, and paragraph is in fact fruitful in support of me, keep up posting these articles.

  32. Vacɦement passionnant, mon petit doigt me dit que ce
    poste intéresserait uun pote

    Takе a look at my homepage salopes africaines

  33. Bon ʝe n’aі ƿoint fini de lire mais je repasserai ce soir

    Also visit mʏ web-site … belle blondinette

  34. Excellent post : cߋmme d’hab

    my weblog whooty

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>