开发者

Simple databinding between textbox and form title

I am new at C# and databinding, and as an experiment I was trying to bind the form title text to a property:

namespace BindTest
{
    public partial class Form1 : Fo开发者_如何学Crm
    {
        public string TestProp { get { return textBox1.Text; } set { } }

        public Form1()
        {
            InitializeComponent();
            this.DataBindings.Add("Text", this, "TestProp");
        }
    }
}

Unfortunately, this does not work. I suspect it has something to do with the property not sending events, but I don't understand enough about databinding to know why exactly.

If I bind the title text directly to the textbox, like this:

this.DataBindings.Add("Text", textBox1, "Text")

Then it does work correctly.

Any explanation about why the first code sample does not work would be appreciated.


You must implement INotifyPropertyChanged interface. Try the following code and see what happens when you remove NotifyPropertyChanged("MyProperty"); from the setter:

private class MyControl : INotifyPropertyChanged
{
    private string _myProperty;
    public string MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            if (_myProperty != value)
            {
                _myProperty = value;
                // try to remove this line
                NotifyPropertyChanged("MyProperty");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

private MyControl myControl;

public Form1()
{
    myControl = new MyControl();
    InitializeComponent();
    this.DataBindings.Add("Text", myControl, "MyProperty");
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    myControl.MyProperty = textBox1.Text; 
}


I think you need to implement the INotifyPropertyChanged Interface. You must implement this interface on business objects that are used in Windows Forms data binding. When implemented, the interface communicates to a bound control the property changes on a business object.

How to: Implement the INotifyPropertyChanged Interface

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜