【问题标题】:How to bind control's two properties to two object properties properly如何正确将控件的两个属性绑定到两个对象属性
【发布时间】:2010-11-23 00:26:04
【问题描述】:

我有一个带有 TextBox 的表单,如下所示:

        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. 在文本框中输入文本
  3. 将焦点转移到其他控件

我在控制台中得到了这个结果:

TextBox lost focus

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

但是当我这样做时:

  1. 运行应用程序
  2. 单击文本框(更改左侧值)

我得到了这个结果:

Moving to right...
Acomplished: X changed

似乎左绑定到 X 有效。而要测试的文本不是。当我将绑定位置更改为此:

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

Text Binding 有效,而 left to X binding 无效。所以总而言之:只有第一个 DataBinding 有效。

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

【问题讨论】:

    标签: c# winforms data-binding binding


    【解决方案1】:

    我一直都是这样的。

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

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      相关资源
      最近更新 更多