Default formatting in WPF application always in US locale

Aljoša Kocen

Migrating in-house applications from WinForms to WPF and MVVM Architecture, has in the most cases been a trully eventfull endeavour. Rocky from time time, and quite eventfull from the learning point of view. I Enjoyed every minute of it.

One thing struck me in the beginning. WPF displays data in US Locale by default. They use dot as a decimal separator, and comma for thousands. US Date by default format is "02/16/2016". In Slovenia, for example, we use commy afor decimal separator, and dot for thousands separator. Date format would be "16.2.2016".

To show you the problem, i whipped up a test app, which creates a dataTable object, and inserts some DateTime and Double type of values in it:

Imports System.Data
Class MainWindow

	Private Data As New DataTable

	Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded

		'Declare some data
		Dim dt As New DataTable
		dt.Columns.Add(New DataColumn("ID", Type.GetType("System.Int32")))
		dt.Columns.Add(New DataColumn("Date", Type.GetType("System.DateTime")))
		dt.Columns.Add(New DataColumn("Value", Type.GetType("System.Double")))

		'Add Some rows to datatable
		For I As Integer = 1 To 10
			dt.Rows.Add(I, New DateTime(2016, 1, i), Math.Round(100 * Microsoft.VisualBasic.Rnd(), 3))

		ResultsGrid.ItemsSource = dt.DefaultView
	End Sub
End Class

And the result is:

Note two things. US DateTime Format and decimal separator. 

To solve this SNAFU, one needs to explicitly tell the app to use system defined locale. We do this by overriding Application OnStartup Event in Application.xaml.vb (or Application.xaml.cs, in C# case):

Imports System.Globalization
Imports System.Windows.Markup

Class Application

	' Application-level events, such as Startup, Exit, and DispatcherUnhandledException
	' can be handled in this file.
	Protected Overrides Sub OnStartup(e As StartupEventArgs)
			New FrameworkPropertyMetadata(
	End Sub
End Class

And the result we get now, is:

Both dates and numbers are now shown correctly for my User locale. 

Note also that DateTime in US Format shows 12:00 AM, and in Slovenian it says 00:00:00. Didn't go into this, but the way it is shown, it seems that the day in the U.S.A. starts at noon? :)

Best regards and Happy Coding.

Tags:  Visual Basic.NET  WPF