WPF MVVM Textbox Validation

前端 未结 2 477
别跟我提以往
别跟我提以往 2021-02-08 11:27

I\'m creating a WPF application using MVVM. I have a textbox, which is bound to a property in my ViewModel of type double with a default value of 0.0. If I now ente

2条回答
  •  旧时难觅i
    2021-02-08 12:07

    You can try following solution. Firstly you should declare DoubleProperty as Nullable:

        public double? DoubleProperty { get; set; }
    

    Then create converter class implemented IValueConverter. It can looks like this:

     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double result;
            if(!double.TryParse((string)value, out result))
            {
                return null;
            }
    
            return result;
        }
    

    Finally, you can use it:

        xmlns:converter="clr-namespace:[TestApplication]"
    
    
        
    
    
    
    

    Now, if user typed wrong values - DoubleProperty will be null.

提交回复
热议问题