[英]WPF/Caliburn.Micro - Input Validation using IDataErrorInfo
I have following code in my WPF application and I'm trying to implement input validation. 我的WPF应用程序中包含以下代码,并且正在尝试实现输入验证。
Model: 模型:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
ViewModel: ViewModel:
public class CustomerViewModel : Screen, IDataErrorInfo
{
private Customer _customer;
public Customer Customer
{
get { return _customer; }
set
{
if (_customer != value)
{
_customer = value;
NotifyOfPropertyChange(() => Customer);
}
}
}
public string Error
{
get
{
throw new NotImplementedException();
}
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Name")
{
if (string.IsNullOrEmpty(Customer.Name))
result = "Please enter a Name";
if (Customer.Name.Length < 3)
result = "Name is too short";
}
return result;
}
}
}
View: 视图:
<TextBox Text="{Binding Customer.Name, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/>
Problem: The solution is not working as expected. 问题:解决方案无法按预期工作。 Nothing happens when type data in Textbox. 在文本框中键入数据时,什么也没有发生。 I'm not sure weather I have followed the right steps. 我不确定天气是否遵循正确的步骤。
Could any one help me? 有人可以帮我吗?
I presume the problem occurs because there is no Name
property in your view model (but inside the Customer
class). 我认为出现此问题是因为视图模型中没有Name
属性(但在Customer
类内部)。 Your work with a nested property in your binding Customer.Name
. 在绑定的Customer.Name
使用嵌套属性的工作。
I have not used this in combination with IDataErrorInfo
validation. 我还没有将此与IDataErrorInfo
验证结合使用。
Currently this condition inside you view model indexer will not be hit: 当前,您在查看模型索引器中的这种情况将不会得到满足:
if (columnName == "Name")
{
...
}
because the indexer is never called. 因为从未调用过索引器。
My suggestion 我的建议
Add a Name
property to your view model which will represent the customers name. 将Name
属性添加到您的视图模型中,该属性将代表客户名称。 You can then initialize your view model with the customer class like setting 然后,您可以使用诸如set之类的客户类来初始化视图模型
Name = customer.Name
in the view models constructor. 在视图模型构造函数中。
Your binding would need to change to 您的绑定将需要更改为
<TextBox Text="{Binding Name ....
After doing this, the indexer should be working, because now there is a Name
property in your view model. 完成此操作后,索引器应该可以工作了,因为现在视图模型中有了Name
属性。
Perhaps there is another solution which would let you keep you current nested binding ( Customer.Name
), but I do not know this for sure. 也许还有另一种解决方案可以让您保持当前的嵌套绑定( Customer.Name
),但我不确定这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.