setter 中的数据绑定和抛出异常
假设我有一个简单的类,
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 中的异常将被吞掉,我将无法执行任何操作直到我更正文本框中的值。 我的意思是文本框将无法失去焦点。 一切都是安静的 - 没有错误 - 在您更正值之前您无法执行任何操作(甚至关闭表单或整个应用程序)。
这看起来像是一个错误,但问题是:解决方法是什么?
Let's say I have a simple class
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;
}
}
}
Then I want to setup a binding for this class:
txtAge.DataBindings.Add("Text", dataSource, "Name");
Now if I enter incorrect age value in the text box (say 200) the exception in the setter will be swallowed and I will not be able to do anything at all until I correct the value in the textbox. I mean the textbox will not be able to loose focus. It's all silent - no errors - you just can't do anything (even close the form or the whole application) until you correct the value.
It seems like a bug, but the question is: what is a workaround for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,解决方案如下:
我们需要处理 BinsingSource、CurrencyManager 或 BindingBanagerBase 类的 BindingComplete 事件。 代码可以如下所示:
Ok, here is the solution:
We need to handle BindingComplete event of BinsingSource, CurrencyManager or BindingBanagerBase class. The code can look like this: