6

假设我有一个简单的课程

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 中的异常将被吞下,并且在我更正文本框中的值之前,我将无法做任何事情。我的意思是文本框将无法失去焦点。这一切都是无声的——没有错误——在你更正值之前,你什么也做不了(甚至关闭表单或整个应用程序)。

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

4

1 回答 1

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();
  }
}
于 2009-05-19T11:39:14.173 回答