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 ever开发者_如何学运维y 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?
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.
You could try POCO Entity Generator or the EF Code-First feature, which is still in CTP.
Both approaches require EF4 though.
Are your properties changed via the same context used by the UI?
If so, edit the T4 file you use to create your entities.
- Make it create INotifyPropertyChanged entities, with properties that notify on changes and have an explicit field behind.
精彩评论