【发布时间】:2010-10-27 04:37:09
【问题描述】:
假设我有一个简单的类
public class Person
{
public string Name { get; set; }
private int _age;
public int Age
{
get { return _age; }
set
{
if(value < 0 || value > 150)
throw new ValidationException("Person age is incorrect");
_age = value;
}
}
}
然后我想为这个类设置一个绑定:
txtAge.DataBindings.Add("Text", dataSource, "Name");
现在,如果我在文本框中输入了错误的年龄值(比如 200),setter 中的异常将被吞没,在我更正文本框中的值之前,我将无法做任何事情。我的意思是文本框将无法失去焦点。这一切都是无声的 - 没有错误 - 在您更正值之前,您无法做任何事情(甚至关闭表单或整个应用程序)。
这似乎是一个错误,但问题是:有什么解决方法?
【问题讨论】:
-
您是否有理由抛出异常而不是实现 IDataErrorInfo?我认为后者是 WinForms 中更惯用的方法(它在 WPF 中仍然可以很好地工作)。
标签: .net winforms data-binding exception setter