I’m having trouble trying to figure out the best way to implement IDataErrorInfo in my WPF application. I have a few models, each with a lot of properties, that are being used. The ViewModel has Properties of each of these models and the View uses these properties to bind to the model. This is a reduced version of the structure I have:
public class ModelA
{
public string PropertyA1 {get; set;}
public string PropertyA2 {get; set;}
}
public class ModelB
{
public string Property B1 {get; set;}
public string Property B2 {get; set;}
}
public class ViewModel
{
public ModelA modelA {get; set;}
public ModelB modelB {get; set;}
}
My questions is – Where do I implement IDataErrorInfo – In the ViewModel or in the Model?
The View binds to these properties as modelA.PropertyA1 and so on so the errors are raised in the Models and not in the ViewModel which makes it necessary to implement IDataErrorInfo in the Models. However, I’ve heard that it’s a good practice to implement validation logic in the ViewModel.
I was wondering if there was a way to catch the errors in the ViewModel without writing a wrapper for each of the properties that would raise an error as there are lots of properties and writing a wrapper for each of them would be tedious.
Thanks for your help!
Thank you for your help guys! Here’s how I decided to solve my problem:
I created two base classes, one for normal models (Ones that don’t have any validations. It only implements INotifyPropertyChanged) and another for models that have validations as shown below.
Now my models looked like this:
Not a huge change there. The ViewModel now looks like this:
This seems to be working for me so far. This way, any new models that have validation need only derive from ValidationModelBase and have the ViewModel add an event handler for the validation event.
If anyone has a better way of solving my problem, do let me know – I’m open to suggestions and improvements.