如何将Windows窗体的自定义属性绑定到第二个属性?

时间:2010-04-16 08:50:53

标签: c# winforms data-binding properties

我想将Windows窗体的自定义属性绑定到第二个属性,所以当我更新前者后,后者获得相同的值。

这是我正在尝试做的最简单的例子:

public partial class Form2 : Form
{       
    public string MyTargetProperty { get; set; }
    public string OtherProperty { get; set; }

    public Form2()
    {
        InitializeComponent();
        this.DataBindings.Add("MyTargetProperty", this, "OtherProperty");        
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MyTargetProperty = "test";
        Console.WriteLine("OtherProperty " + OtherProperty);
    }
}

当我点击button1时,我应该能够看到'OtherProperty'与'MyTargetProperty'具有相同的值。难道我做错了什么?我想念一下吗?

1 个答案:

答案 0 :(得分:3)

您的表单需要为INotifyPropertyChanged实施MyTargetProperty

示例:

class FooForm : Form, INotifyPropertyChanged
{
    private int myTargetProperty;

    public int MyTargetProperty
    {
        get { return this.myTargetProperty; }
        set
        {
            this.myTargetProperty = value;

            this.OnPropertyChanged(
                new PropertyChangedEventArgs("MyTargetProperty"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        var evt = this.PropertyChanged;

        if (evt != null)
            evt(this, e);
    }
}

然后你需要像这样添加绑定:

this.DataBindings.Add(
    "OtherProperty", 
    this, 
    "MyTargetProperty", 
    false, 
    DataSourceUpdateMode.Never);

这将执行单向绑定。当MyTargetProperty发生变化时,OtherProperty将永远不会更新。如果您需要双向绑定,请更改DataSourceUpdateMode并为PropertyChanged实施OtherProperty