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)を入力すると、セッターの例外が飲み込まれ、テキストボックスの値を修正するまで何もできなくなります。つまり、テキストボックスはフォーカスを失うことができなくなります。すべてサイレントで、エラーはありません。値を修正するまで、何もできません(フォームまたはアプリケーション全体を閉じても)。

バグのように見えますが、問題は次のとおりです。これの回避策は何ですか?

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 に答える