setter中的数据绑定和抛出异常 [英] Data Binding and throwing exception in setter

查看:19
本文介绍了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;
    }
  }
}

然后我想为这个类设置一个绑定:

Then I want to setup a binding for this class:

txtAge.DataBindings.Add("Text", dataSource, "Name");

现在,如果我在文本框中输入不正确的年龄值(比如 200),setter 中的异常将被吞下,在我更正文本框中的值之前,我将无法做任何事情.我的意思是文本框将无法失去焦点.一切都是无声的 - 没有错误 - 在您更正值之前,您无法做任何事情(甚至关闭表单或整个应用程序).

Now if I enter incorrect age value in the text box (say 200) the exception in the setter will be swallowed and I will not be able to do anything at all until I correct the value in the textbox. I mean the textbox will not be able to loose focus. It's all silent - no errors - you just can't do anything (even close the form or the whole application) until you correct the value.

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

It seems like a bug, but the question is: what is a workaround for this?

推荐答案

好的,解决方案如下:

我们需要处理 BinsingSource、CurrencyManager 或 BindingBanagerBase 类的 BindingComplete 事件.代码可以是这样的:

We need to handle BindingComplete event of BinsingSource, CurrencyManager or BindingBanagerBase class. The code can look like this:

/* 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();
  }
}

这篇关于setter中的数据绑定和抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆