Search code examples
c#wpfxaml

Storing decimal numbers in double? property using updatesourcetrigger as PropertyChanged


I am using WPF/MVVM. I am binding a textbox.Text to a nullable double in view model. UpdateSourceTrigger = PropertyChanged and not Lostfocus. Hence the double property will be updated when each digit is entered using Double.Parse(textbox.Text) inside the converter I am using. I am using PropertyChanged and converter here since I need to do some other validation checks.

My issue is I need to enter "1.69". When I enter "1", it is added as "1" to the property. Next I enter ".", but it is not added as "1." since double.parse saves the number as "1"

So I can't add decimal numbers. Please help. Thanks in advance.


Solution

  • You should be fine, if you use StringFormat=\{0:n\}. For example:

    <TextBox Text="{Binding FooValue, UpdateSourceTrigger=PropertyChanged, 
                                                   StringFormat=\{0:n\}}"/>
    

    or just use a converter. For example:

    <Window.Resources>        
       <helper:DoubleConverter x:Key="DoubleConverter" />
    </Window.Resources>
    ...The code omitted for the brevity
    <TextBox Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged,       
                            Converter={StaticResource DoubleConverter}}"/>
    

    and DoubleConverter:

    public class DoubleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
           return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
           // return an invalid value in case of the value ends with a point
           return value.ToString().EndsWith(".") ? "." : value;
        }
    }