Tigraine

Daniel Hoelbling-Inzko talks about programming

WPF FormatString and it’s localization bugs

Posted by Daniel Hölbling on September 10, 2010

As some of you may know, I am from Austria. That means that I get to pay my bills in Euro and we format our decimals with a comma instead of a period (yes I know I’m weird).

So naturally my culture setting is de-AT and I really expect to see my decimals formatted this way: € 19,99
Turns out, WPF doesn’t give a damn and if you use FormatString in a binding it will just go ahead and return en-US formats!

<TextBox Text="{Binding Path=Model.Price, StringFormat=\{0:c\}}"/>

This is a bug in WPF and has been there for more than 2 years now from what I can gather. There is a fix to it as suggested by Nir Dobovizki, who coincidentally also has a pretty cool CheatSheet on WPF Databinding that I now have taped to the wall.

For the sake of completeness here is the code you have to put in your App startup code (I’ve thrown it in my App constructor):

FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement), 
    new FrameworkPropertyMetadata(
        XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

While at it I also found out another pretty cool thing that managed to save me a lot of markup in XAML: MultiBinding! You can apply StringFormat to single elements through the {Binding} blocks, but sometimes you want to show stuff like “Showing Page x of y” somewhere.
My naïve approach was to just create 4 elements and bind 2 of them to the appropriate values. As Brian points out in his post on WPF StringFormat you can just do stuff like this:

<TextBlock VerticalAlignment="Center" Margin="0, 0, 0, 10">
    <TextBlock.Text>
        <MultiBinding StringFormat="Showing Page {0} of {1}">
            <Binding Path="CurrentPage" />
            <Binding Path="NumberOfPages" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The StringFormat attribute works exactly like the String.Format method whereas the <Binding> children are the parameters passed into it. Pretty cool to say the least.

Now if only someone explained to me why WPF Grids have this hideous way of cluttering up my markup with Grid.Row=”0” Grid.Column=”1” I may finally make my peace with WPF (aka the display technology I stayed away until now because learning it seemed like an impossible task)

Filed under net, programmierung, wpf
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more