简体   繁体   中英

Implementing IDataErrorInfo in a view model

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM