数据绑定和setter方法​​抛出异常 [英] Data Binding and throwing exception in setter

查看:118
本文介绍了数据绑定和setter方法​​抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个简单的类

Let's say I have a simple class

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)异常的制定者将被吞噬,我不能做任何事情,直到我纠正文本框中的值。我的意思是文本框将无法松动的焦点。这一切都沉默 - 没有错误 - 你不能做任何事情(甚至关闭窗体或整个应用程序),直到纠正值

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?

推荐答案

好吧,这里是解决方案:

Ok, here is the solution:

我们需要处理BinsingSource,CurrencyManager的或BindingBanagerBase类BindingComplete事件。在code可以是这样的:

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天全站免登陆