数据绑定到一个对象的属性实现IEnumerable

数据绑定到一个对象的属性实现IEnumerable

问题描述:

我试图做简单的数据绑定到对象的实例。事情是这样的:

I am trying to do simple data binding to an instance of an object. Something like this:

public class Foo : INotifyPropertyChanged
{
    private int bar;
    public int Bar { /* snip code to get, set, and fire event */ }

    public event PropertyChangedEventHandler PropertyChanged;
}

// Code from main form
public Form1()
{
    InitializeComponent();
    Foo foo = new Foo();
    label1.DataBindings.Add("Text", foo, "Bar");
}

这工作,直到我修改了Foo类来实现IEnumerable,其中T为int,字符串,等等。在这一点上,我得到一个ArgumentException当我尝试添加数据绑定:不能绑定到数据源的属性或列吧。

This works until I modify the Foo class to implement IEnumerable, where T is int, string, whatever. At that point, I get an ArgumentException when I try to add the data binding: Cannot bind to the property or column Bar on the DataSource.

在我而言,我不在乎枚举,我只是想绑定到该对象的非枚举的属性。有没有干净的方式做这个?在现实code,我的类不实现IEnumerable,一个基类几层了链一样。

In my case, I don't care about the enumeration, I just want to bind to the non-enumerable properties of the object. Is there any clean way do to this? In the real code, my class does not implement IEnumerable, a base class several layers up the chain does.

最好的解决方法我有一个瞬间是把对象变成的BindingList只有一个单一的项目,并绑定到。

The best workaround I have a the moment is to put the object into a bindinglist with only a single item, and bind to that.

下面是两个相关的问题:

Here are two related questions:

  • How can I databind to properties not associated with a list item in classes deriving List
  • How can you databind a single object in .NET?

您也许可以创建继承了IEnumerable包含您的类中的一个子类,并绑定到这一点。排序是这样的:

You can probably create a child class contained within your class that inherits from the ienumerable and bind to that. sort of like this:

class A : IEnumerable { ... }
class Foo : A
{
   private B _Abar = new B();
   public B ABar
   {
      get { return _Abar; }
   }
}

class B : INotifyPropertyChanged
{
   public int Bar { ... }
   ...
}

public Form1()
{
    InitializeComponent();
    Foo foo = new Foo();
    label1.DataBindings.Add("Text", foo.ABar, "Bar");
}

这应该可以解决问题。