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

标签 .net winforms data-binding exception setter

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

相关文章:

c# - CheckedListBox 数据源突然不工作

java - 嵌套表单数据与 Spring MVC 中的对象列表绑定(bind)

Android:RecyclerView 的项目不会通过数据绑定(bind)和 Realm 刷新

WPF:使用 DataGridComboBoxColumn 进行数据绑定(bind)

c# - BindingList<> ListChanged 事件

c# - 如何将 .Net Framework 从 3.5 版更改为 4.0 版

c# - 使用 ScheduledTasks 类删除计划作业

c# - 通过 C#.Net 创建/连接 VPN 连接

c# - Windows 窗体 - 列表对话框字符串生成器追加新行

c# - 有没有其他方法可以将 Task.Status 设置为 Canceled