I have seen implementations of numeric TextBox
with code behind in WPF
. How do we do this in MVVM
pattern?
In WPF if you bind the TextBox to a Decimal or a Int Property it will accept only that int or decimal otherwise it will show a red border that it does not have proper value in the binding. And if you are talking about the numeric updown textbox then it is readily available with WPF toolkit over here
honestly - what does MVVM and numeric textbox have in common?
if you want a numeric textbox you create a new TextBox or AttachedProperty or a Behaviour. Here is an example for a MaskedTextbox behaviour to see what i mean.
now to your MVVM part. i assume that you want to validate your input to be just numeric. if your viewmodel has an Property of type int, then your binding just works if your view got input which is convertable to int. otherwise your viewmodel will never be informed. there are 2 ways now:
first: you make sure that your view just can take numeric input (with your numeric textbox) and the viewmodel property can be int.
or second: your viewmodel property type is typeof string and you use IDataErrorInfo to let the view know when the input is not numeric.
By the standard definition of MVVM you would not want a ViewModel behind a custom control. All you should do is extend the TextBox control and ensure only numeric input is entered. You should also add a DependencyProperty that returns the numeric input.
The ViewModel would come in when that control is used in a window or a composite control. You would bind the Text or Numeric DependencyProperty to a public property in your ViewModel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With