首页 > 解决方案 > 使用反射的每个属性的 ValidationRule

问题描述

我正在考虑在 ValidationRule 中使用反射。用户可以在 WPF DataGrid 中输入值,而 DataGrid 的每个单元格都代表底层模型的属性(当然)。

为了避免使用每个单元格(属性)的 if 语句手动检查单元格是否包含无效字符(';'),我打算使用反射来实现。...但是我怎样才能得到使用的类的类型BindigGroup?这有可能吗?

public class MyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        BindingGroup group = (BindingGroup)value;
        StringBuilder error = null;
        foreach (var item in group.Items)
        {
            IDataErrorInfo info = item as IDataErrorInfo;
            if (info != null)
            {
                if (!string.IsNullOrEmpty(info.Error))
                {
                    if (error == null)
                    {
                        error = new StringBuilder();
                    }

                    Type type = typeof(MyClass);
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo property in properties)
                    {
                        Console.WriteLine(property.GetValue(property.Name, null));
                        if (property.GetValue(property.Name, null).ToString().Contains(";"))
                        {
                            error.Append(property.Name + " may not contain a ';'.");
                        }
                    }

                    error.Append((error.Length != 0 ? ", " : "") + info.Error);
                }
            }
        }

        if (error != null)
            return new ValidationResult(false, error.ToString());
        else
            return new ValidationResult(true, "");

    }
}

标签: c#reflectionvalidationrule

解决方案


我找到了这个解决方案:

Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
    Console.WriteLine(property.GetValue(item));
    if ( property.GetValue(item).ToString().Contains(";") )
    {
        error.Append(property.Name + " may not contain a ';'.");
    }
}

推荐阅读