为WPF组合DataAnnotations和IDataErrorInfo [英] Combining DataAnnotations and IDataErrorInfo for WPF

查看:87
本文介绍了为WPF组合DataAnnotations和IDataErrorInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写WPF应用程序,我想使用数据注释来指定Required字段,Range等之类的内容.

I am writing a WPF application and I want to use Data Annotations to specify things like Required Fields, Range, etc.

我的ViewModel类使用常规的INotifyPropertyChanged接口,我可以使用C#4 Validator足够容易地验证整个对象,但是如果它们没有正确验证,我还希望这些字段以红色突出显示.我在这里找到此博客文章(http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii.aspx ),其中讨论了如何编写基本视图模型以实现IDataErrorInfo并仅使用Validator,但该实现实际上并未编译,我也看不到它如何工作.有问题的方法是这样的:

My ViewModel classes use the regular INotifyPropertyChanged interface and I can validate the entire object easily enough using the C# 4 Validator, but I would also like the fields to highlight red if they do not validate properly. I found this blog post here (http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/28/wpf-data-validation-using-net-data-annotations-part-ii.aspx) that talks about how to write your base view model to implement IDataErrorInfo and simply use the Validator, but the implementation doesn't actually compile nor can I see how it would work. The method in question is this:

    /// <summary>
    /// Validates current instance properties using Data Annotations.
    /// </summary>
    /// <param name="propertyName">This instance property to validate.</param>
    /// <returns>Relevant error string on validation failure or <see cref="System.String.Empty"/> on validation success.</returns>
    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
        {
            throw new ArgumentException("Invalid property name", propertyName);
        }

        string error = string.Empty;
        var value = GetValue(propertyName);
        var results = new List<ValidationResult>(1);
        var result = Validator.TryValidateProperty(
            value,
            new ValidationContext(this, null, null)
            {
                MemberName = propertyName
            },
            results);

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

        return error;
    }

问题是未提供GetValue.他可能在谈论继承DependencyObject时出现的GetValue,但是语法仍然不起作用(希望您将DependencyProperty作为参数传递),但是我在在设置器上被调用.

The problem is GetValue is not provided. He could be talking about the GetValue that comes when you inherit DependencyObject, but the syntax still doesn't work (it expects you to pass DependencyProperty as a parameter) but I'm using regular CLR properties with OnPropertyChanged("MyProperty") being invoked on the setter.

是否有将验证连接到IDataErrorInfo接口的好方法?

Is there a good way to connect the validation to the IDataErrorInfo interface?

推荐答案

使用上面的代码作为起点,我通过IDataErrorInfo进行了此工作.

Using your above code as a starting point I got this working through IDataErrorInfo.

您的问题集中在仅拥有属性名称时获取属性的值,在这里反射可以有所帮助.

Your problem centred around getting the value of the property when you only have the property name, reflection can help here.

public string this[string property]
{
   get
   {
      PropertyInfo propertyInfo = this.GetType().GetProperty(property);
      var results = new List<ValidationResult>();

      var result = Validator.TryValidateProperty(
                                propertyInfo.GetValue(this, null),
                                new ValidationContext(this, null, null)
                                {
                                  MemberName = property
                                }, 
                                results);

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

      return string.Empty;
   }
}

这篇关于为WPF组合DataAnnotations和IDataErrorInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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