Click here to Skip to main content
15,883,705 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF: Binding non-textual content to textboxes in the correct localization

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Mar 2012CPOL1 min read 10.7K   64   2
Double and DateTime values bound to textboxes in correct format

Introduction

Ever tried to bind a double value to a textbox in a non-English application? The number gets formatted in US English style, though you need something totally different: typically a decimal comma in place of a decimal point.

When searching the web for solutions, you may find such strange ideas like a custom value converter. Using string properties in your view model could also help. Others will tell you that you have to localize your application.

How to do it correctly

The last idea shows the correct way – but you do need not follow it completely. While a thread inherits its language (i.e., CurrentCulture and CurrentUICulture) from Windows, some WPF components do not. A single line of code helps (use it e.g. in MainWindow()):

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

OK, let’s go a step further. On your non-English Windows, you want to show data in American style. For that purpose, add a key to the application settings in the app.config file:

XML
<add key ="UILanguage" value="en-US"/>

Now set the CurrentUICulture to your value, and also replace CultureInfo.CurrentCulture.IetfLanguageTag with your value.

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(uiLanguage);

Double and DateTime values are now shown correctly in TextBoxes. But the DatePicker remains in your Windows settings. Add one more line, and set the CurrentCulture also. Now it works!

The sample project provides you with a small demo to play with.

Why is WPF so much more complicated than Windows Forms?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestion.NET 4.0 Pin
Richard Deeming2-Apr-12 9:33
mveRichard Deeming2-Apr-12 9:33 
GeneralRe: .NET 4.0 Pin
Bernhard Hiller2-Apr-12 20:23
Bernhard Hiller2-Apr-12 20:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.