2009-05-18 9 views
5

データバインディングとセッタのスロー例外

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"); 

ここで、私がテキストボックスの値を修正するまで、セッターの中にあるものは飲み込まれ、私は何もすることができません。私は、テキストボックスがフォーカスを失うことができないことを意味します。それはすべて静かです。エラーはありません。値を修正するまで、何もできません(フォームやアプリケーション全体を閉じることさえできます)。

これはバグのようですが、問題は次のようなものです:これに対する回避策は何ですか?

+1

IDataErrorInfoを実装するのではなく、例外をスローする理由はありますか?私は、後者はWinFormsの方が慣れ親しんだアプローチだと思っています(WPFでもうまくいきます)。 –

答えて

3

[OK]を、ここでのソリューションです。コードは次のようになります。

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

huuh ... IDataErrorInfoの実装について考える –

関連する問題