![](/img/trans.png)
[英]How to dynamically query IQueryable array by each property using reflection?
[英]ValidationRule for each property using reflection
我正在考慮在ValidationRule中使用反射。 用戶可以在WPF DataGrid中輸入值,而DataGrid的每個單元格都代表基礎模型的屬性(當然)。
為了避免使用每個單元格(屬性)的if語句手動檢查單元格是否包含無效字符(';'),我打算使用反射來對此進行檢查。 ...但是如何獲取BindigGroup
使用的類的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 ';'.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.