UPDATE: I wrote a more in dept post about getting Wpf to pick up regional settings and even update them on the fly
There is a new version of the WPF Data Binding Cheat Sheet, there is a small block of code you have to add to any WPF application in order to correctly format dates and numbers using data binding (I define “correct” as what the user would expect), read on for the full details and the required code for your copy-paste pleasure.
By default, when you use data binding and the target property is a string, WPF will format your value using the US English culture and net the user’s settings.
On the other hand, if you bind to an object property then the .net framework will do the conversion - and will do the right thing.
For example, those two lines:
<Label Content="{Binding Source={x:Static s:DateTime.Now}}"/>
<TextBlock Text="{Binding Source={x:Static s:DateTime.Now}}"/>
Will produce the same text (but with different margin) on a US English machine, on machine with different date format the first line will give the correct result while the second line will keep using the US English settings.
To correct this (in my opinion very serious) bug you have to add the following code before showing any GUI:
FrameworkElement.LanguageProperty.OverrideMetadata
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(
CultureInfo.CurrentCulture.IetfLanguageTag)));
The beginning of the application’s Startup event seems a good place.
If you use the default WPF project template add the bold line to your App.xaml:
<Application x:Class="MyProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml"
Startup="Application_Startup">
<Application.Resources>
And in your App.xaml.cs file add:
private void Application_Startup(object sender, StartupEventArgs e)
{
FrameworkElement.LanguageProperty.OverrideMetadata
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(
CultureInfo.CurrentCulture.IetfLanguageTag)));
}
Download The Cheat sheet Here
posted @ Sunday, February 22, 2009 5:15 PM