gpt4 book ai didi

.net - setter中的数据绑定(bind)和抛出异常

转载 作者:行者123 更新时间:2023-12-04 20:25:55 25 4
gpt4 key购买 nike

假设我有一个简单的类(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;
}
}
}

然后我想为这个类设置一个绑定(bind):
txtAge.DataBindings.Add("Text", dataSource, "Name");

现在,如果我在文本框中输入不正确的年龄值(比如 200),setter 中的异常将被吞下,并且在我更正文本框中的值之前,我将无法做任何事情。我的意思是文本框将无法失去焦点。这一切都是无声的——没有错误——在你更正值之前,你什么也做不了(甚至关闭表单或整个应用程序)。

这似乎是一个错误,但问题是:解决方法是什么?

最佳答案

好的,这是解决方案:

我们需要处理 BinsingSource、CurrencyManager 或 BindingBanagerBase 类的 BindingComplete 事件。代码可能如下所示:

/* Note the 4th parameter, if it is not set, the event will not be fired. 
It seems like an unexpected behavior, as this parameter is called
formattingEnabled and based on its name it shouldn't affect BindingComplete
event, but it does. */
txtAge.DataBindings.Add("Text", dataSource, "Name", true)
.BindingManagerBase.BindingComplete += BindingManagerBase_BindingComplete;

...

void BindingManagerBase_BindingComplete(
object sender, BindingCompleteEventArgs e)
{
if (e.Exception != null)
{
// this will show message to user, so it won't be silent anymore
MessageBox.Show(e.Exception.Message);
// this will return value in the bound control to a previous correct value
e.Binding.ReadValue();
}
}

关于.net - setter中的数据绑定(bind)和抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/880357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com