开发者

How can I bind a custom property of a windows form to a second property?

开发者 https://www.devze.com 2022-12-26 21:07 出处:网络
I want to bind a custom property of a windows form to a second property, so when I update the f开发者_JAVA百科ormer the latter gets the same value.

I want to bind a custom property of a windows form to a second property, so when I update the f开发者_JAVA百科ormer the latter gets the same value.

This is the simplest example of what I'm trying to do:

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);
    }
}

When I click button1 I should be able to see that 'OtherProperty' has the same value as 'MyTargetProperty'. Am I doing something wrong? Do I miss something?


Your form needs to implement INotifyPropertyChanged for the MyTargetProperty.

Example:

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);
    }
}

Then you need to add the binding like this:

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

This will perform a one way binding. The MyTargetProperty will never be updated when the OtherProperty changes. If you need a two way binding you change the DataSourceUpdateMode and also implement a PropertyChanged for OtherProperty.

0

精彩评论

暂无评论...
验证码 换一张
取 消