【问题标题】:BindingList<T> where T is interface that implements other interfaceBindingList<T> 其中 T 是实现其他接口的接口
【发布时间】:2011-12-04 10:39:47
【问题描述】:

我坚持使用 BindingList,其中 T 是扩展 A 接口的接口。当我在绑定中使用这个 bindingList 时,只有来自 T 的属性是可见的,而来自继承的 A 接口的属性不可见。为什么会这样?它看起来像一个 .net 错误。我需要我的 2 个项目来共享一些通用功能。当从 baseImplementation 传输 PropertyChanged 事件时,绑定列表的 PropertyDescriptor 也为空。 附加的接口和实现。到底是SetUp方法

interface IExtendedInterface : IBaseInterface
{
    string C { get; }
}

interface IBaseInterface : INotifyPropertyChanged
{
    string A { get; }
    string B { get; }
}

public class BaseImplementation : IBaseInterface
{
    public string A
    {
        get { return "Base a"; }
    }

    public string B
    {
        get { return "base b"; }
        protected set
        {
            B = value;
            OnPropertyChanged("B");
        }
    }

    protected void OnPropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(p));
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}

public class ExtendedImplementation : BaseImplementation, IExtendedInterface
{
    public string C
    {
        get { return "Extended C"; }
    }
}

 private void SetupData()
    {
        BindingList<IExtendedInterface> list = new BindingList<IExtendedInterface>();
        list.Add(new ExtendedImplementation());
        list.Add(new ExtendedImplementation());
        dataGridView1.DataSource = list;
    }

【问题讨论】:

  • 尽量不要在文件中附加代码。我们不需要整个项目。将您的示例分解为尽可能小的程序,并将其粘贴为文本/代码。
  • “不可见”是什么意思?如果您绑定到这些属性,它们可能会显示为不可访问,但这只是设计时绑定的结果,当您运行应用程序时应该一切正常。
  • 它们在绑定网格中不可见,当从绑定列表触发 ItemChanged 事件时,如果它涉及来自 BaseInterface 的属性,那么我得到 null PropertyDescriptor。应用程序运行时它不工作。只需粘贴代码并查看。由于我的代表,我无法发布图片

标签: c# interface bindinglist inherited


【解决方案1】:

属性是通过(间接)TypeDescriptor.GetProperties(typeof(T)) 获得的,但行为符合预期。来自接口的属性从不返回,即使来自基于类的模型,除非它们在该类型的公共 API 上(对于接口,意味着 在直接类型上)。类继承是不同的,因为这些成员仍然在公共 API 上。当一个接口:ISomeOtherInterface,即“实现”,而不是“继承”。举一个简单的例子说明这可能是一个问题,考虑(完全合法):

interface IA { int Foo {get;} }
interface IB { string Foo {get;} }
interface IC : IA, IB {}

现在; IC.Foo 是什么?

可能可以通过为接口注册一个自定义 TypeDescriptionProvider 或使用 ITypedList 来解决这个问题,但这两者都很棘手。老实说,数据绑定与类相比更容易使用接口。

【讨论】:

  • 感谢您的解释。这将有助于在未来避免绑定到接口的问题。
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2012-10-15
  • 1970-01-01
  • 2021-09-18
  • 2017-08-11
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
相关资源
最近更新 更多