[英]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. 但是,当更改myProperty.innerProperty
时,不会引发任何事件 - 从不通知BindingSource更改。
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." 我已经读过 ,解决方法是“确保当innerProperty
对象引发PropertyChanged
事件时,包含innerProperty
的MyProperty
类会捕获事件,并且还会引发自己的PropertyChanged
事件。”
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? 是否有一个体面的解决方法来使实体可绑定?
You have to implement INotifyPropertyCHanged on your class. 你必须在你的课上实现INotifyPropertyCHanged。
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. 我不确定这是否适用于winforms。 It works for WPF and Silverlight. 它适用于WPF和Silverlight。
Are your properties changed via the same context used by the UI? 您的属性是否通过UI使用的相同上下文进行了更改?
If so, edit the T4 file you use to create your entities. 如果是这样,请编辑用于创建实体的T4文件。
- Make it create INotifyPropertyChanged entities, with properties that notify on changes and have an explicit field behind. - 使其创建INotifyPropertyChanged实体,其属性通知更改并具有明确的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.