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

https://gist.github.com/OlsonAndrewD/5623505 << Whee, my first Gist!

Now I can write this:

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s