13

If I bind Text in a TextBox to a float Property then the displayed text doesn't honor the system decimal (dot or comma). Instead it always displays a dot ('.'). But if I display the value in a MessageBox (using ToString()) then the correct System Decimal is used.

enter image description here

Xaml

<StackPanel>
    <TextBox Name="floatTextBox"
             Text="{Binding FloatValue}"
             Width="75"
             Height="23"
             HorizontalAlignment="Left"/>
    <Button Name="displayValueButton"
            Content="Display value"
            Width="75"
            Height="23"
            HorizontalAlignment="Left"
            Click="displayValueButton_Click"/>
</StackPanel>

Code behind

public MainWindow()
{
    InitializeComponent();
    FloatValue = 1.234f;
    this.DataContext = this;
}
public float FloatValue
{
    get;
    set;
}
private void displayValueButton_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(FloatValue.ToString());
}

As of now, I've solved this with a Converter that replaces dot with the System Decimal (which works) but what's the reason that this is neccessary? Is this by design and is there an easier way to solve this?

SystemDecimalConverter (in case someone else has the same problem)

public class SystemDecimalConverter : IValueConverter
{
    private char m_systemDecimal = '#';
    public SystemDecimalConverter()
    {
        m_systemDecimal = GetSystemDecimal();
    }
    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString().Replace('.', m_systemDecimal);
    }
    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString().Replace(m_systemDecimal, '.');
    }
    public static char GetSystemDecimal()
    {
        return string.Format("{0}", 1.1f)[1];
    }
}
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266

1 Answers1

10

Looks like there's a solution for this:

http://www.nbdtech.com/Blog/archive/2009/03/18/getting-a-wpf-application-to-pick-up-the-correct-regional.aspx

Here is another discussion that can possibly help:

http://connect.microsoft.com/VisualStudio/feedback/details/442569/wpf-binding-uses-the-wrong-currentculture-by-default

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141
  • +1, this is great! Thanks! Don't have time to go through the links you provided right now, but I'll check them as soon as I get time. So I'll wait a couple of hours before accepting your answer to see if someone else comes up with something! Great work – Fredrik Hedblad Jan 27 '11 at 12:25