views:

50

answers:

2

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 : Form
    {
        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.

+1  A: 

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

Leniel Macaferi
Thanks for the link, this is the big piece I was missing. However, it appears that the value also needs to always be set through the property for this to work, so in my example the TextChanged handler is also required.
bde
+1  A: 

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; 
}
šljaker
+1 for including the TextChanged handler is needed so that the property is set, that was another piece that I was missing.
bde