本文介绍了数据注释,IDataErrorInfo的和MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到MVVM来验证数据的最佳方式。
目前,我试图用IDataErrorInfo的使用MVVM模式数据注释。

I'm trying to find the best way to validate data in MVVM.Currently, I'm trying to use IDataErrorInfo with Data Annotations using the MVVM pattern.

但是,似乎没有任何工作,我不知道我可能是做错了。我有这样的事情。

However, nothing seems to work and I'm not sure what I could be doing wrong. I have something like this.

public class Person : IDataErrorInfo
{
    [Required(ErrorMessage="Please enter your name")]
    public string Name { get; set; }

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            return OnValidate(propertyName);
        }
    }

    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
            throw new ArgumentException("Property may not be null or empty", propertyName);

        string error = string.Empty;

        var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
        var results = new List<ValidationResult>();

        var context = new ValidationContext(this, null, null) { MemberName = propertyName };

        var result = Validator.TryValidateProperty(value, context, results);

        if(!result)
        {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
        }
        return error;
    }
}



在的(这个答案不符合我的标准很可惜。)

Model code courtesy of the solution at How to catch DataAnnotations Validation in MVVM (This answer does not meet my criteria unfortunately.)

public class PersonViewModel
{
    private Person _person;

    public string Name
    {
        get
        {
            return _person.Name
        }
        set
        {
            _person.Name = value;
        }
    }
}





<Label Content="Name:" />

<TextBox Text="{Binding UpdateSourceTrigger=LostFocus,
                        Path=Name,
                        ValidatesOnDataErrors=True,
                        NotifyOnValidationError=true}" />





有什么办法,以保持模型之间的分离,查看,并同时仍利用数据注解的验证与IDataErrorInfo的?


Is there any way to keep the seperation between model, view, and viewmodel while still utilizing data annotations for validation with IDataErrorInfo?

推荐答案

要保持验证运行, IDataErrorInfo的必须由数据上下文,该属性绑定到控制来实现。因此,它应该是这样的:

To keep validation running, IDataErrorInfo must be implemented by the data context, which property is bound to the control. So, it should be something like:

public class PersonViewModel : IDataErrorInfo 
{
    [Required(AllowEmptyStrings = false)]
    public string Name
    {
        get
        {
             return _person.Name
        }
        set
        {
             _person.Name = value;
        }
    }    

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            return OnValidate(propertyName);
        }
    }

    protected virtual string OnValidate(string propertyName)
    {
        /* ... */
    }
}

有没有必要实施 IDataErrorInfo的在模型中,这是视图模型的责任。通常情况下, IDataErrorInfo的是由您的视图模型的基类来实现。

There's no need to implement IDataErrorInfo in model, this is view model's responsibility. Usually, IDataErrorInfo is implemented by the base class for your view models.

顺便说一句,为什么的OnValidate 受到保护?你如何想象这种方法的重写?

By the way, why OnValidate is protected? How do you imagine overriding of this method?

这篇关于数据注释,IDataErrorInfo的和MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 02:23