2011-07-18 11 views
1

Winformsには2つのテキストボックスがあります。 textBox2は、プロパティUnitにバインドされます。 ユニットまたはtextBox2の変更がそれぞれtextBox2またはユニットを自動的に更新することを希望します。しかし、それはしません。 ここにWinformのコードの3つのバージョンがあります。結合1つのセットデータは、それは二つの方法の自動更新を持つことになりますが、イベントハンドラ、イベントハンドラWinforms双方向のデータボックスDataBindingが正常に動作しない

textBox2を更新するためにハードコードで

public partial class Receiver : Form, INotifyPropertyChanged 
{   

    private int unit=0; 
    public int Unit 
    { 
     get { return unit; } 
     set 
     { 
      if (value != unit) 
      { 
       unit = value;           
      } 
     } 
    } 

    public Receiver() 
    { 
     InitializeComponent();    
     textBox2.DataBindings.Add("Text", Unit, "Unit"); 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     //textBox1 change makes Unit change, 
     //I wish the change will be displayed in textBox2 automatically 
     Unit = Convert.ToInt32(textBox1.Text); 
    }   
} 

バージョン2が動作しません願ってい

バージョン

しかし、textBox2の変更は、自動的にユニットを更新しません。

バージョン3なぜイベントハンドラを使用するのか、このようにするだけです。

public partial class Receiver : Form, INotifyPropertyChanged 
{ 
    private int unit=0; 
    public int Unit 
    { 
     get { return unit; } 
     set 
     { 
      if (value != unit) 
      { 
       unit = value; 
       textBox2.text = unit.toString();       
      } 
     } 
    } 

    public Receiver() 
    { 
     InitializeComponent();    
     textBox2.DataBindings.Add("Text", Unit, "Unit"); 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     Unit = Convert.ToInt32(textBox1.Text);   
    } 

    private void textBox2_TextChanged(object sender, EventArgs e) 
    { 
     Unit = Convert.ToInt32(textBox2.Text);   
    } 
} 

}

バージョン2バージョン3は問題がある、textbox1への変更はtextbox2に更新が発生します。それはCPUサイクルの多くを引き起こします。マウスフォーカスがtextBox1のままになってからアップデートを行うのが最善の方法です。だからそれを行う方法?

答えて

5

あなたのコードに問題がラインである:

textBox2.DataBindings.Add("Text", Unit, "Unit"); 

あなたはそのプロパティではありませんプロパティ自体を保持しているインスタンスによってデータソースを置き換える必要があり、ここであなたは、データソースの更新モードのセットを特定すべきですそれはDataSourceUpdateMode.OnPropertyChangedになります。従って:

textBox2.DataBindings.Add("Text", this, "Unit", false, DataSourceUpdateMode.OnPropertyChanged); 

//test using the second or the third approach: 
Unit = 15;//now the textBox2.Text equals to 15 too. 

textBox2.Text = 12;//now Unit equals 12 too 
関連する問題