c# - 使用 BindingSource 绑定(bind)到嵌套属性 - 或者,使实体可绑定(bind)

标签 c# .net winforms entity-framework data-binding

绑定(bind)到嵌套属性非常简单:

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

但是,当 myProperty.innerProperty 发生更改时,不会引发任何事件 - BindingSource 永远不会收到更改通知。

我已经 read解决方案是 “确保当 innerProperty 对象引发 PropertyChanged 事件时,包含 MyProperty 类innerProperty 捕获事件并引发它自己的 PropertyChanged 事件。”

然而, Entity Framework does not do this for me ,并且我宁愿不遍历每个类的每个实例并将自定义方法连接到每个导航属性,只是为了使我的类可绑定(bind)。 是否有使实体可绑定(bind)的合适的解决方法?

最佳答案

你必须在你的类上实现 INotifyPropertyCHanged。

您的属性(property)应该看起来像这样。

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));
        }
    }

我不确定这是否适用于 winforms。它适用于 WPF 和 Silverlight。

关于c# - 使用 BindingSource 绑定(bind)到嵌套属性 - 或者,使实体可绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5070990/

相关文章:

c# - WPF:异步进度条

c# - 使用 Array.CreateInstance 和 new 运算符实例化数组的区别

c# - Connection must be valid and open错误

c# - 如何将多个 RichTextBox 内容写入一个 RTF 文件并保留每个 RichTextBox 的字体格式

C# 应用求解二次虚根

c# - 如何在一个项目中使用两个不同的 Microsoft Interop 程序集?

.net - 将 DotnetZip 与 Visual Studio C++/CLR 结合使用

.net - 无法在生成的程序集中获取应用程序实例(Razor 引擎)?

c# - 为什么这个 LINQ 查询可以编译?

c# - 如何滚动到富文本框中的字符串