Embedding IDataErrorInfo in a View Model

I have a ViewModel class with a Phone object as one of its properties, a ViewModel is set in my main window data context, I need to implement IDataErrorInfo in the base class of the phone model or in the ViewModel class that contains the Phone property

Also would be the right way to bind a text box that I'm trying to check on my ViewModel.NewPhone.StringProperty?

Thank you very much

+4
source share
1 answer

The decision on where to implement IDataErrorInfo really depends on your application logic. For example, you might have a Phone class that implements it in such a way as to not allow any invalid phone numbers, but in your view model you would only want to allow US numbers.

It is usually good practice to implement IDataErrorInfo both in your model and in view mode, and in case the view model is not found, forward the model request. Then you will be attached to the viewmodel, as usual.

 public string this[string propertyName] { get { if (propertyName == "PhoneNumber") { if (!IsUSNumber(PhoneNumber)) { return "Non-US number."; } } // No validation errors found by the viewmodel // Forward to model IDataErrorInfo implementation return Model[propertyName]; } } 

I recommend that the model implement the basic validations that are relevant to each phone, for example, the format of the phone number, and that the presentation model uses type-specific checks that may differ from the view for viewing, for example, only for US phone numbers or numbers, owned by a particular provider.

+6
source

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


All Articles