Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Decimal separators in Silverlight

I run English Windows with regional settings set to Slovenian, which means I’m also using a comma (,) for my decimal separator character, not a dot (.), which is mostly used in English-speaking countries.

Silverlight sees my configuration as:

CultureInfo.CurrentCulture: sl-SI
CultureInfo.CurrentUICulture: en-US

And with my current setup I still have to use a dot for my decimal separator. To test this, I created a business object with numeric (decimal) property and use a TwoWay-bound TextBox on it.

Typing a comma-separated value into the box
 
and tabbing out of it, gets me

whereas entering a dot-separated value

leaves me with
 

Silverlight is clearly ignoring my regional settings so what can I do to make this work?

Rather than catching keystrokes and convert dots into commas etc., one simple solution comes in a form of a value converter, which would use a CurrentCulture when converting a number between string and decimal:

public class CultureNumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((decimal)value).ToString(CultureInfo.CurrentCulture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal returnValue;
if (decimal.TryParse(value.ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out returnValue))
{
return returnValue;
}
return value;
}
}

 
Here’s a full solution sample: