Thursday, 3 June 2010

StringFormats in Binding Expressions

Do I have a bee in my bonnet about Culture settings? Maybe I do, but in this case it's a little annoying and it's to do with String.Format (quite possibly my favourite method in the whole of the .NET framework). So in WPF, if I do something like:

MessageBox.Show(string.Format("Price: {0:C}", 123.45));

I get a little message box showing me "Price: £123.45" (because my regional settings are en-GB, you see).

If, however, I use a binding expression like this one:

Binding="{Binding Path=Price, StringFormat={}{0:C}}"

It doesn't matter what my regional settings are, it'll always show up as USD. Now I can kind of see why this might be - the binding expression is stored in an xml file and of course xml files can have language settings, but it does smack to me of a bit of a miss, a dare-I-say-it, "design feature". After a bit of digging around, notably this forum discussion, I came up with the following, less coding solution. Place the following code in your App.xaml code-behind:

protected override void OnStartup(StartupEventArgs e)
{
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(
CultureInfo.CurrentCulture.IetfLanguageTag)));

base.OnStartup(e);
}


Clearly, this will only work if you want EVERY element to use your local settings.

No comments: