Search code examples
c#wpfvalidationxamltelerik

Telerik RadMaskedNumericInput allow empty value


My goal is to get a MaskedNumericInput box, where numbers between 0-9999 are allowed. Its value is bound to an integer.

<telerik:RadMaskedNumericInput Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WpfExt:RadGridViewExt}}, Path=DataContext.MaxInvoicesPerConcatenationFile, Mode=TwoWay}"
                               Mask="#4"  UpdateValueEvent="LostFocus" TextMode="PlainText"
                               maskedInput:MaskedInputExtensions.Maximum="9999"/>

I'm not using any kind of validator or something. It seems that there maybe is like an internal validator. If I clear my box, it will be highlighted red with the error message:

"Value "" could not be converted."

Is there any way I could get it working with an empty value?

Is there any way to allow the input to be empty?


Solution

  • You can set the AllowNull attached property to False, then the error is gone and the value 0 will be set to the bound property when clearing the masked input box, although it is displayed empty.

    <telerik:RadMaskedNumericInput Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type WpfExt:RadGridViewExt}}, Path=DataContext.MaxInvoicesPerConcatenationFile, Mode=TwoWay}"
                                   Mask="#4"  UpdateValueEvent="LostFocus" TextMode="PlainText"
                                   maskedInput:MaskedInputExtensions.Maximum="9999"
                                   maskedInput:MaskedInputExtensions.AllowNull="False"/>
    

    Contrary to the documentation, the AllowNull property is set true by default, not false. This way, when clearing the input, the value would be set to null, but since your bound property of type int cannot be null, you will get this error. From the documentation on AllowNull:

    By default the RadMaskedNumericInput and RadMaskedCurrencyInput don't allow you to set null to their Value property. Instead the null value is coerced to 0. To alter this behavior and allow null values you can set the MaskedInputExtensions.AllowNull attached property to True.

    That being said, an alternative is to change your property to be of the nullable type int?, which will set null when the input box is cleared without any error being displayed, but you will have to deal with the null value in your view model. It is up to your requirements which approach fits best.