代码之家  ›  专栏  ›  技术社区  ›  nightcoder

setter中的数据绑定和引发异常

  •  5
  • nightcoder  · 技术社区  · 17 年前

    假设我有一个简单的班级

    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中的异常将被忽略,在我更正文本框中的值之前,我将无法执行任何操作。我的意思是,文本框不能失去焦点。一切都是无声的-没有错误-你只是不能做任何事情(甚至关闭窗体或整个应用程序),直到你改正了这个值。

    这看起来像一个bug,但问题是:解决这个问题的方法是什么?

    1 回复  |  直到 17 年前
        1
  •  4
  •   nightcoder    17 年前

    好的,下面是解决方案:

    我们需要处理bindingSource、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();
      }
    }
    
    推荐文章