2009-08-27 23 views
1

私はTextBoxを持って、それは左の値を変更します。このTextBoxはXプロパティを持つクラスにバインドされています。今度は私のTextBoxのLeft値を変更すると、私のクラスのXを更新したいと思います。データバインドされたクラスプロパティの更新を強制するにはどうすればよいですか?TextBox Leftを変更するとバインドされたクラスのX値が更新されるようにするにはどうすればよいですか?

+0

(コメントに返信)私はテキストボックスからderrivedまし –

答えて

3

データバインディングの仕組みのため、このタイプの双方向バインディングは、コントロールが変更をアドバタイズする場合にのみ機能します。通常は*Changedイベント経由 - つまりLeftChangedです。そのようなイベントはないので、TextBoxをサブクラス化し、(newLeftを再宣言し、を追加してLocationChangedをフックすることができません。

イベントをLocationChangedに追加して手動で行うことはできますか?または、位置/左を設定するときにオブジェクトを手動で更新するだけですか?


using System; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    class SuperTextBox : TextBox 
    { 
     protected override void OnLocationChanged(EventArgs e) 
     { 
      base.OnLocationChanged(e); 

      EventHandler handler = (EventHandler)Events[LeftChangedKey]; 
      if (handler != null) handler(this, EventArgs.Empty); 
     } 
     public event EventHandler LeftChanged 
     { 
      add { Events.AddHandler(LeftChangedKey, value); } 
      remove { Events.RemoveHandler(LeftChangedKey, value); } 
     } 
     public new int Left 
     { 
      get { return base.Left; } 
      set { base.Left = value; } 
     } 
     private static readonly object LeftChangedKey = new object(); 
    } 
    class Person { 
     private int value; 
     public int Value { 
      get {return value;} 
      set { 
       this.value = value; 
       EventHandler handler = ValueChanged; 
       if(handler!=null) 
       { 
        handler(this, EventArgs.Empty); 
       } 
      } 
     } 
     public event EventHandler ValueChanged; 
    } 
    static class Program 
    { 
     static void Main() 
     { 
      Button btn; 
      TextBox txt; 
      Person p = new Person { Value = 10 }; 
      using (Form form = new Form { 
       DataBindings = {{ "Text", p, "Value"}}, 
       Controls = { 
        (txt = new SuperTextBox { 
         DataBindings = {{ "Left", p, "Value", false, 
          DataSourceUpdateMode.OnPropertyChanged}} 
        }), 
        (btn = new Button { 
         Text = "bump", 
         Dock = DockStyle.Bottom 
        }) 
       } 
      }) { 
       btn.Click += delegate { txt.Left += 5; }; 
       Application.Run(form); 
      } 
     } 
    } 
} 
+0

はLocationChangedが発射されるときに発生する新たな左とLeftChangedイベントを追加しました。しかしそれでも動作しません。何かお見逃しですか? –

+0

はい、バインディングはすぐに更新するように設定する必要があります(onpropertychanged) - 私は例を追加しました。 –

+0

ありがとうございます。できます。 –

関連する問題