开发者

When to call the IDataErrorInfo's AddError method

I have a ViewModel class that implements the IDataErrorInfo Interface.

In each property's set I validate the value passed in and if it fails the validation I call a method called AddError to add an error for the property. The AddError method adds an item into my underlying data type I'm using to manage the errors (a Dictionary(Of String, List(Of String))).

Currently things are working well during data entry. If the user enters invalid values for a property, the FrameworkElement that is used to input the data is highlighted with the ToolTip set to the error message.

Now, here's my problem.

Say my object contains invalid fields from the start.... For example, if I have a Person class with a required field "Name" and I create a new instance of the Person class. The Name Field will not be highlighted as an "error" because the Name Property's set method hasn't been called yet.

So, I put validation into the property's get as well.

This seems to works but......it feels like a hack. And some property validation has to be done by the model (as opposed to the ViewModel that I'm working with). The 开发者_如何学运维Model bubbles up the appropriate error message that should be set but I can't get the error message unless I set the Model's property.

Any advise on the best approach to implementing the IDataErrorInfo interface would be really really appreciated.

Thanks!

-Frinny


I figured out something that doesn't feel like a hack.

I also probably should have mentioned that I have a base class that all my ViewModel inherit from. It is in this base class that I am implementing the IDataErrorInfo Interface.

What I ended up doing was adding a new MustOverride method to the base ViewModel class called "Validate" that validates the property name supplied to it. If the validation fails then it adds an entry into my underlying errors dictionary.

I call the validate method in the Item property (that implements the IDataErrorInfo.Item property).

This way each derived class can contain it's own validation code and I can be sure that the method exists because it's part of the base ViewModel class.

If this isn't the best approach, please let me know.

-Frinny

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜