Does Winforms DataBinding work for programmatically changed properties?

I have UI controls that use the DataBindings.Add method and it works if I manually change the specified UI property, or the original object has changed outside of it.

But if I call the UI.Property = value in the code, then it doesn't change the UI or the original object specified for the DataBindings.Add.

What am I doing wrong? Am I using it wrong?

+2


source to share


1 answer


The control will not know that something has changed if the object does not implement INotifyPropertyChanged

. Then the setter property on the object is changed to raise the event PropertyChanged

by passing in the property name that was changed in the event arguments.

INotifyPropertyChanged

is the specific interface that the data binding engine in WinForms looks for when connecting the data binding. If it sees an object that implements that interface, it will subscribe to its event, and you will see your UI updated automatically without specifying that the data bindings re-read their values ​​(which is what happens if you reassign DataSource

, etc. .).

Not obvious, but it makes sense when you think. Without broadcasting the event, how does the UI control know that the property has changed? He doesn't knock over real estate as often. It should be said that the property has changed and the event PropertyChanged

is the usual way to do it.

Something like (uncompressed code) ...




public class MyInterestingObject : INotifyPropertyChanged
{
    private int myInterestingInt;

    public event PropertyChangedEventHandler PropertyChanged;

    public int MyInterestingInt
    {
       get { return this.myInterestingInt; }
       set
       {
           if (value != this.myInterestingInt)
           {
               this.myInterestingInt = value;
               this.RaisePropertyChanged("MyInterestingInt");
           }
       }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
             handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

      

Now any code that is bound to this object MyInterestingInt

will be updated when this property is changed. (Some people like proxies for implementing this interface for them.)

Caveat: make sure you set the updated value before raising the event PropertyChanged

! This is easy to do and can leave you scratching your head about why the value isn't updating.

+8


source







All Articles