by Svetlozar Angelov
18. January 2010 16:33
Suppose we want to bind a TextBlock.Text to a DateTime.Now – the first step is to add the namespace -
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Then the binding -
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat=D}"/>
It looks fine, short and clean, but unfortunately it doesn’t… For some reason in the biding system by default, WPF uses en-US as the culture, regardless of the system settings. So if you are with Bulgarian locale settings (Like I am) this doesn’t work (the date is in English). Of course there is a workaround, you have to change the used culture by hand. This must be done before any GUI created, so a good place to put the code is into the Startup EventHandler -
<Application x:Class="WpfApplication2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup"
StartupUri="Window1.xaml">
</Application>
and the actual implementation -
private void Application_Startup(object sender, StartupEventArgs e)
{
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement)
, new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}
The culture is changed, the Date is ok.