使用反射的每个属性的验证规则



我正在考虑在验证规则中使用反射。用户可以在 WPF 数据网格中输入值,而数据网格的每个单元格表示基础模型的属性(当然)。

为了避免手动检查单元格是否包含无效字符(';'),每个单元格(属性)都有一个 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, "");
    }
}

我找到了这个解决方案:

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 ';'.");
    }
}

最新更新