c# - 使用反射的每个属性的 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, "");
}
}
解决方案
我找到了这个解决方案:
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 ';'.");
}
}
推荐阅读
- python - 关于将字符串反序列化回Python中的树的函数中的参数问题
- firefox - Fedora - Tor 代理拒绝连接?
- c# - 动态处理电子邮件附件
- oracle - 插入查询不在块内执行
- performance - 当我只想要前 10 个存储桶时,是否可以更快地进行弹性搜索聚合?
- java - 如何在 IntelliJ 中安装 javax.servlet 的文档?
- javascript - 如何将具有静态项的类转换为模块文件
- angular - 子组件无法在 Angular 9 中加载
- android - Android - 从自定义相机中删除水印
- reactjs - 如何使用 Material UI 重构显示表单的重复代码