Implementing IDataErrorInfo in a view model

给你一囗甜甜゛ 提交于 2019-12-07 05:30:11

问题


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

Also what would be the correct way to bind the textbox I'm trying to validate to my ViewModel.NewPhone.StringProperty?

Many thanks


回答1:


The decision of where to implement IDataErrorInfo really depends on your application's logic. For example, you could have your Phone class implement it in a way that doesn't allow any invalid phone numbers, but in your viewmodel you'd like to only allow numbers from the US.

Usually a good practice is to implement IDataErrorInfo in both your model and viewmodel, and in case no error was found by the viewmodel, forward the request to the model. Then you'll bind 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's IDataErrorInfo implementation
        return Model[propertyName];
    }
}

I recommend having the model implement the basic validations which are relevant for every phone, like phone number format, and have the viewmodel implement the view-specific validations that may vary from view to view, such as only allowing US phone numbers or numbers that belong to a certain provider.



来源:https://stackoverflow.com/questions/13113779/implementing-idataerrorinfo-in-a-view-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!