Skip to content
May 21, 2013 / Andrew

Binding StringFormat in XAML – A Workaround

I’ve often wished I could have a dynamic StringFormat in a XAML binding. For example:

<TextBlock Text="{Binding SomeValue, StringFormat={Binding SomeFormat}}" />

Unfortunately this isn’t possible because StringFormat isn’t a dependency property, so I usually do the formatting in my view model and bind to the formatted value without using StringFormat.

Today I wrote some attached properties that get the job done without making my view model responsible for the formatting. (I don’t think it’s bad to have the view model responsible for the formatting; this is just another alternative.) << Whee, my first Gist!

Now I can write this:

  local:StringFormatHelper.Format="{Binding SomeFormat}"
  local:StringFormatHelper.Value="{Binding SomeValue}"
  Text="{Binding (local:StringFormatHelper.FormattedValue)}"

It’s a little more verbose than the XAML I would’ve liked to write, and maybe that’s why I didn’t find anything like it during my web searches. But it was a fun little exercise.


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