Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BindingSource to bind to Nested Properties - or, Making Entities Bindable

Binding to a nested property is easy enough:

checkBox1.DataBindings.Add(new Binding("Checked", bindingSource, "myProperty")); //Normal binding
checkBox2.DataBindings.Add(new Binding("Checked", bindingSource, "myProperty.innerProperty")); //Nested property

However, when myProperty.innerProperty is changed, no events are raised - the BindingSource is never notified of the change.

I've read that the solution is to "make sure that when the innerProperty object raises the PropertyChanged event, the MyProperty class that contains innerProperty captures the event and also raises a PropertyChanged event of its own."

However, entity framework does not do this for me, and I'd rather not go through every instance of every class and wire-up a custom method to every navigation property, just to make the my classes bindable. Is there a decent workaround to make entities bindable?

like image 904
BlueRaja - Danny Pflughoeft Avatar asked Feb 21 '11 20:02

BlueRaja - Danny Pflughoeft


1 Answers

You have to implement INotifyPropertyCHanged on your class.

Your property should look something like this.

private bool _checked;
    public bool Checked
    {
        get { return _checked; }
        set
        {
            if (value != _checked)
            {
                _checked = value;
                OnPropertyChanged("Checked");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyCHanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

I'm not sure if this works for winforms. It works for WPF and Silverlight.

like image 117
Marco Avatar answered Nov 08 '22 23:11

Marco