Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Regional date formats and Silverlight 4

0.00/5 (No votes)
2 Oct 2011 1  
How to get Silverlight 4 to display dates by default using the regional settings in the Control Panel.

I am writing a Silverlight application which will be used in multiple countries by a large organisation. The users are all used to working in English, so there's no requirement for a complex internationalization approach.


However, the one thing which causes major annoyance is for dates to appear in the American mm/dd/yyyy format in the rest of the world.


So I was rather upset when I realised that although my PC is set to the UK regional settings, my Silverlight app ignored this and insisted on formatting DateTime fields as mm/dd/yyyy when, for example, I displayed a date in a DataGrid column.


My initial attempts to fix this found me loads of articles about complex internationalization techniques in Silverlight and .NET, and it started to look as though I'd have no choice but to write custom-handlers for all my date fields.


Fortunately, I then discovered some references to the System.Windows.Markup.XmlLanguage class. All I needed to do was add a few lines to my MainPage() routine as follows:


C#
using System.Windows.Markup;
using System.Threading;
.....
    public MainPage()
    {       
     this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
     // Now the rest of the constructor as it was before
     InitializeComponent();
       ......

and suddenly my dates looked as I wanted them to.


Depending on the way you structure your code, you may need to add a similar line in the constructors of other UI elements, but so far I've found that just this one line does the trick.


To be honest, I don't really understand why this behaviour isn't the default. Silverlight knows perfectly well what language you want - the main thread has the information - but it doesn't propagate that up to the UI elements unless you do it explicitly.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here