【发布时间】:2013-10-04 10:43:04
【问题描述】:
我正在我的 ViewModel 中实现 IDataErrorInfo。
我有两个属性 'Nom' 和 'Prenom',我想强制
#region IDataErrorInfo
string IDataErrorInfo.Error
{
get { return null; }
}
string IDataErrorInfo.this[string propertyName]
{
get { return GetValidationError(propertyName); }
}
#endregion IDataErrorInfo
#region Validation
private static readonly string[] ValidatedProperties = { "Nom", "Prenom" };
public bool IsValid
{
get
{
foreach (string property in ValidatedProperties)
if (GetValidationError(property) != null)
return false;
return true;
}
}
private string GetValidationError(string propertyName)
{
string error = null;
switch (propertyName)
{
case "Nom":
error = ValidateNom();
break;
case "Prenom":
error = ValidatePrenom();
break;
}
return error;
}
private string ValidateNom()
{
if (string.IsNullOrWhiteSpace(Nom))
{
return "Last name is mandatory";
}
return null;
}
private string ValidatePrenom()
{
if (string.IsNullOrWhiteSpace(Prenom))
{
return "First name is mandatory";
}
return null;
}
我正在像这样绑定我的 TextBox 的 Text 属性:
<TextBox Text="{Binding Nom,
ValidatesOnDataErrors=True,
UpdateSourceTrigger=LostFocus,
NotifyOnValidationError=True}" />
我的问题是:文本框在失去焦点之前显示错误(在应用启动时)。
我正在这样做(在点击事件中),所以它应该在点击之后而不是之前显示错误:
if (!IsValid)
return;
【问题讨论】:
-
这不是正常行为,因为空字段未通过验证吗?您可能需要使用
UpdateSourceTrigger=Explicit以按照您希望的方式进行这项工作。 -
我改成Explicit,结果还是一样
-
@Sheridan 让我抓狂的是,我没有在应用启动时进行 IsValid 测试 :(
-
@Schneider:当数据绑定引擎第一次绑定属性时,它会验证它们。为什么不应该这样做?
-
因为你在验证方法中定义的
null是无效的,而且你已经设置了NotifyOnValidationError=True,那么你期望什么呢?我总是在属性的验证函数中忽略null(例如ValidateNom),但会在你的情况IsValid的主要验证中检查它是否为空或空;
标签: c# wpf mvvm idataerrorinfo