Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF XAML StringFormat DateTime: Output in wrong culture?

I'm having some trouble with the output of a DateTime value. My computer's current culture is set to de-AT (Austria).

The following code

string s1 = DateTime.Now.ToString("d");
string s2 = string.Format("{0:d}", DateTime.Now);

results in s1 and s2 both having the correct value of "30.06.2009".

But when using the same format in XAML

    <TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat=d}"/>

the output is `"6/30/2009". It seems the XAML StringFormat ignores the current culture settings. This happens on both Vista and XP.

I don't want to specify a custom format, because the output should be formatted in the user's preferred culture setting.

Anybody with the same problem? Is this a bug in WPF?

like image 432
Christian Hubmann Avatar asked Jun 30 '09 07:06

Christian Hubmann


3 Answers

Please see my answer on StringFomat Localization problem

like image 105
loraderon Avatar answered Oct 22 '22 02:10

loraderon


To apply the solution mentioned at http://tinyurl.com/b2jegna do the following:

(1) Add a Startup event handler to the Application class in app.xaml:

<Application x:Class="MyApp"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    ...
    Startup="ApplicationStartup">

(2) Add the handler function:

private void ApplicationStartup(object sender, StartupEventArgs e)
{
    FrameworkElement.LanguageProperty.OverrideMetadata(
        typeof(FrameworkElement),
        new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}

WPF strings should then be formatted correctly according to culture.

like image 15
Stephen Holt Avatar answered Oct 22 '22 03:10

Stephen Holt


Wrote about it some time ago on my blog:

This will tell you how to get WPF to use the right culture:

http://www.nbdtech.com/blog/archive/2009/02/22/wpf-data-binding-cheat-sheet-update-the-internationalization-fix.aspx

This will change the WPF culture on the fly when you modify the settings in the control panel:

http://www.nbdtech.com/blog/archive/2009/03/18/getting-a-wpf-application-to-pick-up-the-correct-regional.aspx

like image 10
Nir Avatar answered Oct 22 '22 02:10

Nir