Bernhard Hiller
Bernhard Hiller

Reputation: 2397

How to localize a DatePicker?

In a small Wpf application, use a DatePicker bound to a DateTime property. When the user's region and language settings, and number and date format are German, the date is displayed in German, and the calendar shows German month names. Now I wanted to get it in US-English. In the c'tor of MainWindow I added before InitializeComponent() (same situation when doing that after InitializeComponent()):

string uiLanguage = ConfigurationManager.AppSettings["UILanguage"]; //"en-US"
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(uiLanguage);
FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(uiLanguage)));

While that works with textboxes, it has no effect with the DatePicker. Then I was cheaky and created a new user "John English", logged in as "John English", set his display language to English and the date and number format to US-English. Now the DatePicker always displays the date in the US-English format and the calendar shows English month names, even when I set the language of my program to German. How can that be resolved? Can it be resolved at all?

Upvotes: 3

Views: 10974

Answers (2)

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

In the codebehind of the App.xaml add the following code:

public App()
{
    EventManager.RegisterClassHandler(typeof(DatePicker), DatePicker.LoadedEvent, new RoutedEventHandler(DatePicker_Loaded));
}

void DatePicker_Loaded(object sender, RoutedEventArgs e)
{
    var dp = sender as DatePicker;
    if (dp == null) return;

    var tb = GetChildOfType<DatePickerTextBox>(dp);
    if (tb == null) return;

    var wm = tb.Template.FindName("PART_Watermark", tb) as ContentControl;
    if (wm == null) return;

    wm.Content = "[Put your text here]";
}

[Ontopic ;)] Try setting both CurrentCulture and CurrentUICulture.

//Set default culture to Nl
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

ref for GetChildOfType

Upvotes: 7

user4186147
user4186147

Reputation:

Create a normal DataGridTextColumn without any bindings in the XAML:

<DataGridTextColumn x:Name="SomeDateDataGridColumn" Width="Auto" Header="Header"/> 

Then set the binding and stringformat in the code behind:

SomeDateDataGridColumn.Binding = new Binding("Property") { StringFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern };

Upvotes: 0

Related Questions