在视图模型实现IDataErrorInfo的 [英] Implementing IDataErrorInfo in a view model

查看:241
本文介绍了在视图模型实现IDataErrorInfo的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电话对象,我的主要窗口数据上下文设置为视图模型的属性之一ViewModel类,做我需要实现包含电话财产标的手机模型类或ViewModel类IDataErrorInfo的?

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?

此外,这将是给我想验证我的ViewModel.NewPhone.StringProperty文本框绑定正确的方法是什么?

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

非常感谢

推荐答案

在哪里执行决策 IDataErrorInfo的真的取决于你的应用程序的逻辑。例如,你可以有你的电话类实现它的方式,不允许任何无效的电话号码,但在你的视图模型,你想只允许数字美国

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.

通常是一个很好的做法是贯彻落实 IDataErrorInfo的在模型和视图模型两者,如果没有错误是由视图模型中发现,将请求转发到模型中。然后你会绑定到视图模型照常进行。

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.

这篇关于在视图模型实现IDataErrorInfo的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆