Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric text box with MVVM Pattern

I have seen implementations of numeric TextBox with code behind in WPF. How do we do this in MVVM pattern?

like image 732
katie77 Avatar asked Sep 27 '11 20:09

katie77


3 Answers

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

like image 107
Nivid Dholakia Avatar answered Nov 13 '22 17:11

Nivid Dholakia


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.

like image 32
blindmeis Avatar answered Nov 13 '22 17:11

blindmeis


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.

like image 1
Josh Avatar answered Nov 13 '22 16:11

Josh