您可以通过让验证规则的第一步是调用值转换器来确定它正在验证的值是否可用,从而避免重复逻辑。
当然,这会将您的验证规则与值转换器耦合,除非您创建一个验证规则来搜索绑定以找出正在使用的值转换器。但是如果你开始走这条路,你可能很快就会想到,就像很多人一样,“等等,如果我使用的是 MVVM,我在搞什么价值转换器?”
编辑:
如果您的 ViewModel 实现IDataErrorInfo
了,这确实是唯一的生存方式,那么将值转换器挂钩到属性设置器中相对简单,而无需编写大量特定于属性的验证逻辑。
在您的 ViewModel 类中,创建两个私有字段:
Dictionary<string, string> Errors;
Dictionary<string, IValueConverter>;
在构造函数中创建它们(并填充第二个)。此外,对于IDataErrorInfo
:
public string this[string columnName]
{
return Errors.ContainsKey(columnName)
? Errors[columnName]
: null;
}
现在实现这样的方法:
private bool ValidateProperty(string propertyName, Type targetType, object value)
{
Errors[propertyName] = null;
if (!Converters.ContainsKey(propertyName))
{
return true;
}
try
{
object result = Converters[propertyName].ConvertBack(value, targetType, null, null)
return true;
}
catch (Exception e)
{
Errors[propertyName] = e.Message;
return false;
}
}
现在你的属性设置器看起来像这样:
public SomeType SomeProperty
{
set
{
if (ValidateProperty("SomeProperty", typeof(SomeType), value))
{
_SomeProperty = value;
}
}
}