NumericUpDown issues
Invalid cast exception when NumericUpDown text box is cleared
When the text box of NumericUpDown is entirely cleared of input, the control may throw an invalid cast exception, e.g., Invalid cast from string to decimal?
To prevent these exceptions appearing, try the following:
- Set
TargetNullValueandFallbackValueon yourBinding(both to0). Ensure the values are explicitly typed to match the source property type (usuallydecimalorint) so they are treated as numbers rather than astring. This stops the empty text box from logging as a binding failure. - (Optional) Set
UpdateSourceTrigger=LostFocusto stop the view model updating during edit states. This can reduce occurrences, but doesn't prevent them entirely.
<NumericUpDown Minimum="0" Maximum="10000000">
<NumericUpDown.Value>
<Binding Path="Units">
<Binding.TargetNullValue><x:Decimal>0</x:Decimal></Binding.TargetNullValue>
<Binding.FallbackValue><x:Decimal>0</x:Decimal></Binding.FallbackValue>
</Binding>
</NumericUpDown.Value>
</NumericUpDown>