简体   繁体   English

使用BindingSource绑定到嵌套属性 - 或者,使实体可绑定

[英]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事件时,包含innerPropertyMyProperty类会捕获事件,并且还会引发自己的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。

You could try POCO Entity Generator or the EF Code-First feature, which is still in CTP . 您可以尝试POCO实体生成器或EF代码优先功能,它仍然在CTP中

Both approaches require EF4 though. 这两种方法都需要EF4。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM