我有一个模型:
public class Product
{
public int Rating { get; set; }
...
}
和一个 View 模型:
public class ProductViewModel: IDataErrorProvider
{
public int Temperature { get; set; }
public Product CurrentProduct { get; set; }
public string this[string columnName]
{
get
{
if (columnName == "Rating")
{
if (CurrentProduct.Rating > Temperature)
return "Rating is too high for current temperature";
}
return null;
}
}
}
我的 View 有一个 ProductViewModel 实例作为 DataContext。该 View 具有以下字段:
<TextBox Text={Binding Path=CurrentProduct.Rating, ValidatesOnDataErrors=True} .../>
默认情况下,验证发生在绑定(bind)对象 (Product) 的 IDataErrorProvider 上,而不是 DataContext (ProductViewModel)。所以在上面的例子中,从不调用 ProductViewModel 验证。这只是一个简单的例子,但说明了问题。该模型不知道(也不应该)知道温度,因此设计规定 VM 应该在该字段上执行验证。
是的,我可以破解它并直接在 ViewModel 中复制模型的绑定(bind)属性,但我认为必须有一种更简单的方法将调用重定向到 VM 而不是模型?
最佳答案
如果您希望您的 View 模型通过 IDataErrorInfo 验证名为“Rating”的属性,那么您的 View 模型实际上必须具有一个名为 Rating 的属性并且您必须绑定(bind)到它,这意味着在 View 模型中复制模型的绑定(bind)属性.
无论如何这blog article您可能会感兴趣(Validating Business Rules in MVVM)。作者在 View 模型可以设置的模型中添加了一个验证委托(delegate)。这使您可以使用未知的数据来验证您的模型,例如示例中的温度。
关于c# - IDataErrorInfo 调用绑定(bind)对象而不是 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12792494/