【问题标题】:Data Binding and throwing exception in settersetter中的数据绑定和抛出异常
【发布时间】:2010-10-27 04:37:09
【问题描述】:

假设我有一个简单的类

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

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

【问题讨论】:

  • 您是否有理由抛出异常而不是实现 IDataErrorInfo?我认为后者是 WinForms 中更惯用的方法(它在 WPF 中仍然可以很好地工作)。

标签: .net winforms data-binding exception setter


【解决方案1】:

好的,解决方法如下:

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

【讨论】:

  • huuh ...考虑实现IDataErrorInfo
  • @PeterGfader 我见过在业务对象上实现IDataErrorInfo 的示例。但我认为这样的做法并不完全正确。例如,想象一个模型附加了 2x 视图。两个视图共享IDataErrorInfo 的相同实现。第一个视图有无效的输入数据。第二个有有效数据。但是IDataErrorInfo 实现不能“知道”它属于哪个视图。接口没有定义这样的连接。所以,我认为 ViewModels 应该实现IDataErrorInfo,而不是业务对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2011-05-30
  • 2020-02-14
  • 2013-05-24
  • 2021-03-17
  • 1970-01-01
  • 2013-06-24
相关资源
最近更新 更多