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

时间:2009-08-26 17:43:41

标签: .net winforms data-binding

我正在尝试将简单的数据绑定到对象的实例。像这样:

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,string,等等。此时,当我尝试添加数据绑定时,我得到一个ArgumentException:无法绑定到DataSource上的属性或列Bar。

在我的情况下,我不关心枚举,我只想绑定到对象的非可枚举属性。这有什么干净的方法吗?在实际代码中,我的类没有实现IEnumerable,这是一个基类连接几层的基类。

我目前最好的解决方法是将对象放入只有一个项目的绑定列表中,然后绑定到该绑定列表。

以下是两个相关问题:

1 个答案:

答案 0 :(得分:0)

你可以创建一个包含在你的类中的子类,它继承自ienumerable并绑定到它。有点像这样:

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

这应该可以解决问题。

相关问题