Saturday, September 11, 2010

Windows Phone 7 Quick Tip #2 – Missing StringFormat Attribute

One of my favorite features introduced into Silverlight 4.0 was the ability to use StringFormat with the following syntax:

<TextBlock Text=”{Binding Cost, StringFormat=\{0:c\} }” />

This allows for a pretty much flawless implementation of data binding.

Here’s a not-so-simple, yet not-so-difficult work around.  The idea is to use value converters.

Step 1: Create a value converter as described in Tim Heuer’s post:

http://timheuer.com/blog/archive/2008/07/30/format-data-in-silverlight-databinding-valueconverter.aspx

Step 2: Rather than adding your value converter to the local user control where it’s used, add it to the App.xaml file resources, this allows for easy inclusion into anywhere within your application.  Make sure you add the namespace for the converter at the top of your app.  Then simply create a resource with a key that describes the converter.

image

Step 3: Use your value converter in the controls XAML:

<TextBlock Text=”{Binding Cost, Converter={Static Resource CurrencyConverer}” />

Obviously this isn’t as clean or as flexible as using StringFormat, however it’s not all that bad of a solution.

-twb

2 comments:

  1. I'm behind the curve here. I think you're saying that this SL4 feature is not available in WP7. Does WP7 implement only SL3?

    ReplyDelete
  2. BillVo, AFAIK WP7 is mostly SL3 :(

    Though rumor has it the next big update will pull WP7 into modern SL times

    ReplyDelete