如何正确地将控件的两个属性绑定到两个对象属性

时间:2009-08-26 13:48:05

标签: c# winforms data-binding binding

我有一个带有TextBox的Form,就像这样:

        Form f = new Form();
        TextBox t = new TextBox ();
        t.Click += new EventHandler(t_Click);
        t.LostFocus += new EventHandler(t_LostFocus);

        Testus tt = new Testus();

        t.DataBindings.Add("Left", Testus , "X");
        t.DataBindings.Add("Text", Testus , "Test");

        f.Controls.Add(t);
        f.ShowDialog();

和Testus这样的课程:

class Testus
{
    public string Test
    {
        get
        {
            return _text;
        }
        set
        {
            Console.WriteLine("Acomplished: text change");
            _text = value;
        }
    }
    private string _text;

    public int X
    {
        get
        {
            return x;
        }
        set
        {
            Console.WriteLine("Acomplished: X changed");
            x = value;
        }
    }
    int x;

    public Testus()
    {

    }
}

如您所见,我将TextBox绑定到Testus类。具体来说,我将TextBox.Left绑定到Testus.X,将TextBox.Text绑定到Testus.Test。我想知道更改Controls Left值会影响Testus.X值,反之亦然。 TextBox.Text与Testus.Test相同。

我为TextBox控件的Click和LostFocus添加了处理程序,如下所示:

    static void t_LostFocus(object sender, EventArgs e)
    {
        Console.WriteLine("TextBox lost focus");
    }

    static void t_Click(object sender, EventArgs e)
    {
        Console.WriteLine("Moving to right...");
        ((Control)sender).Left = 100;
    }

我做了这个测试:

  1. 运行应用程序
  2. 在TextBox中输入文字
  3. 将焦点转移到其他控件
  4. 我在控制台中得到了这个结果:

    TextBox lost focus
    

    就是这样! Testus.Test不会改变它的价值!?

    但是当我这样做时:

    1. 运行应用程序
    2. 点击文本框(更改左侧值)
    3. 我得到了这个结果:

      Moving to right...
      Acomplished: X changed
      

      似乎Binding Left to X工作。和文本测试没有。当我将更改绑定位置时:

          t.DataBindings.Add("Text", Testus , "Test");
          t.DataBindings.Add("Left", Testus , "X");
      

      比文本绑定工作而左边的X绑定没有。总而言之:只有第一个DataBinding有效。

      所以我的问题是:如何将TextBox(Left,Text)的两个属性绑定到我的对象(Testus)的两个属性(X,Test),这样它才能正常工作?

1 个答案:

答案 0 :(得分:0)

我总是这样做。

Binding b = new Binding("Test");  
b.Source = tt;  
t.SetBinding(TextBox.TextProperty, b);
相关问题