0

I have a property on my view model of type decimal?. NULL should be a valid value for this property, but when I erase the text from the DecimalUpDown control, a validation error occurs and the property is not given the value NULL (whatever it was previously remains).

The control is declared in xaml like:

<xctk:DecimalUpDown ValueChanged="UpDownBase_OnValueChanged" Text="{Binding ServiceSize}" Minimum="0" Grid.Column="4" Grid.Row="2"  Margin="5" IsEnabled="{Binding IsEditable}"/>

It will bind correctly if I enter a number enter image description here

But as soon as the number is erased a validation error occurs, and the value can't be set back to NULL (in this case the model still has "5" as the value for "ServiceSize"). enter image description here

Validation.GetHasError() returns true for this control. Can I remove the Validation Rules entirely somehow?

ryan
  • 1,451
  • 11
  • 27
  • You can try using IValueConverter to handle null input in-case you are using data binding. – jegtugado May 30 '16 at 23:51
  • @Ephraim I tried that before but I guess I didn't do it correctly as I got it working after rewriting the converter from scratch. If you add an answer some sample code I can accept it – ryan May 31 '16 at 20:12

1 Answers1

0

You can implement an IValueConverter to handle empty input.

public class DecimalUpDownValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        // handle input on a case-to-case basis
        if(value == null)
        {
            // Do something
            return 0;
        }
        else
        {
            return value;
        }
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        // Do the conversion from model property to DecimalUpDownValue
        return value;
    }
}

On your view: (Assuming you added the DecimalUpDownValueConverter as a static resource)

<xctk:DecimalUpDown ValueChanged="UpDownBase_OnValueChanged" Text="{Binding ServiceSize, Converter = { StaticResource DecimalUpDownValueConverter }}" Minimum="0" Grid.Column="4" Grid.Row="2"  Margin="5" IsEnabled="{Binding IsEditable}"/>
jegtugado
  • 5,081
  • 1
  • 12
  • 35
  • If you want empty input to be parsed as null, in ConvertBack use `return string.IsNullOrEmpty((string)value) ? null : value;` – Lionet Chen Sep 30 '21 at 07:24