Search code examples
c#wpfwpf-extended-toolkit

Allow NULL in a WPF Extended Toolkit DecimalUpDown control


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?


Solution

  • 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}"/>