Numeric text field with MVVM pattern

I saw implementations of numeric TextBox with code in WPF . How to do this in the MVVM template?

+6
source share
5 answers

honestly - what is common between MVVM and a numeric text field?

if you want the numeric text field to create a new TextBox or AttachedProperty or Behavior. Here is an example of MaskedTextbox behavior to see what I mean.

now to your part of MVVM. I assume that you want your input to be just numeric. if your viewmodel has a property of type int, then your binding just works if your view received an input that can be converted to int. otherwise your viewmodel will never be informed. Now there are 2 ways:

first: you make sure your view can simply accept numerical input (with your numeric text field), and the viewmodel property can be int.

or second: your viewmodel property type is a typeof string, and you use IDataErrorInfo to give an idea when the input is not numeric.

+4
source

In WPF, if you bind a TextBox to a decimal or Int object, it only accepts this int or decimal value, otherwise it will show a red border that does not have the proper value in the binding. And if you are talking about the numeric text field updown, then it is easily accessible using the WPF toolkit above .

+4
source

By standard MVVM definitions, you won't want a ViewModel behind a custom control. All you have to do is expand the TextBox control and provide only numeric input. You should also add DependencyProperty, which returns numeric input.

The ViewModel will appear when this control is used in a window or composite control. You are binding a Text or Numeric DependencyProperty to a public property in the ViewModel.

+1
source

Well ... if you want to be notified in your viewmodel when the text property of a numeric text field has changed, just contact it. If the .Text property in the numeric text field is not a dependency property, click on the encoder!

this one: http://wpftoolkit.codeplex.com/wikipage?title=DecimalUpDown&referringTitle=Home

I can recommend, and you can bind it to the viewmodel with:

 <!-- View: --> <NumericTextBox Text="{Binding MyViewModelTextStringProperty}" /> 
 //ViewModel: public string MyViewModelTextStringProperty { get/set with NotifyPropertyChanged.... } 
0
source

If you really wanted to do this in the ViewModel, you need to make your linked object a string. Make sure the binding is updated every time you press a key (using UpdateSourceTrigger ).

In your setter, reject non-numeric values ​​by throwing an exception or trimming non-numeric characters. The latter approach has the advantage of working for copy / paste operations, where the embedded text may contain a combination of numbers and letters, but only numbers should be saved.

However, I agree with other suggestions that having a specialized control that provides only a numerical property is a more understandable approach.

Hi,

Eric

0
source

Source: https://habr.com/ru/post/898171/


All Articles