问题
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?
回答1:
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.
回答2:
You could try POCO Entity Generator or the EF Code-First feature, which is still in CTP.
Both approaches require EF4 though.
回答3:
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.
来源:https://stackoverflow.com/questions/5070990/using-bindingsource-to-bind-to-nested-properties-or-making-entities-bindable