数据绑定并在setter中抛出异常

时间:2009-05-18 23:59:39

标签: .net winforms data-binding exception 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),那么设置器中的异常将被吞下,在我更正文本框中的值之前,我将无法执行任何操作。我的意思是文本框无法放松焦点。这一切都是沉默的 - 没有错误 - 你只是不能做任何事情(甚至关闭表格或整个应用程序),直到你纠正价值。

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

1 个答案:

答案 0 :(得分:4)

好的,这是解决方案:

我们需要处理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();
  }
}