我正在追踪如何从我的ViewModel中获取IDataErrorInfo.this [string propertyName]方法中的字符串。
基本上,我在模型中创建了一个新属性,所以我可以验证模型集合中的每一行,并且在我的vaildation检查中,我会说它是否有效,如果不是,它将禁用我的命令viewmodel
模型
string IDataErrorInfo.this[string propertyName]
{
get
{
// Vaildation logic
if (result != string.Empty)
{
IsValid = false;
}
else
{
IsValid = true;
}
return result;
}
视图模型
public bool CanSave
{
get
{
if (m_ProductVersion != null && m_ProductVersion.ProductItems != null)
{
foreach (ProductItem item in m_ProductVersion.ProductItems)
{
// I dont want to use isValid any more
if (!item.IsValid)
return false;
}
}
return true;
}
}
但是如果可以的话,我想摆脱isValid属性并使用viewmodel中IDataErrorInfo的结果。
可以这样做吗?
谢谢
答案 0 :(得分:2)
首先请注意,您的IsValid
无效。想象一下,您有3个要验证的属性:A
,B
和C
。 WPF通常会在您输入内容时评估IDataErrorInfo
,因此请设想我为A
和B
输入无效内容。我收到错误,IsValid
将为false
。到现在为止还挺好。现在,我输入C
有效的内容。 A
和B
仍然无效,但IsValid
现在仍然为真 - 因为最后一次IDataErrorInfo
检查产生了空结果。
因此,您的IsValid
仅检查已验证的 last 属性,这对于一般有效性检查来说绝对不够。
在返回结果之前,属性IsValid
应运行每个属性的验证。像这样:
public bool IsValid ()
{
for (string propertyName in allPropertyNames)
{
if (!string.IsEmptyOrNull(((IDataErrorInfo)this)[propertyName]))
return false;
}
return true;
}
您需要维护所有属性名称的列表,以便我们可以遍历这些名称。然后我们将验证委托给调用this[propertyName]
验证的IDataErrorInfo
。如果我们得到任何错误,则该对象无效。
因此,正如您所看到的,您只需调用IDataErrorInfo
项属性即可替换单个属性检查,但通常需要检查 all < / em> properties。
答案 1 :(得分:2)
我怀疑您错误地实施了IDataErrorInfo
接口。请查看我对Stack Overflow上长期标题为WPF command binding with input validation - how to enable the “save” button only if all input is valid的问题的答案。以这种方式设置界面(您可以忽略其他属性&#39;错误&#39;等),然后您可以像这样访问错误string
:
string error = dataItem.Error;
如果你扩展界面的功能,就像我的示例所示,那么你可以处理多个错误,你可以这样做:
ObservableCollection<string> errors = dataItem.Errors;
或者这个:
public bool CanSave
{
get { return !dataItem.HasErrors; }
}