【问题标题】:Databinding to the properties of an object that implements IEnumerable数据绑定到实现 IEnumerable 的对象的属性
【发布时间】:2010-11-23 02:40:22
【问题描述】:

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

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,而链上几层的基类实现了。

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

这里有两个相关的问题:

【问题讨论】:

  • 对于这个问题,您还有其他解决方案吗?我也遇到了这个问题,无法将属性返回值更改为 BindingList
  • 我不记得找到一个好的解决方案。我想我决定不对这种类型的对象使用数据绑定。
  • 谢谢。我创建了一个 BindingAdapter,它接受一个 ExpressionTree 并且只包含一个属性进行绑定。 ExpressionTree 支持比 WinForms 的默认绑定更多的功能。我现在可以将 textedit 绑定到列表的特定项目等等。我正在创建一个动态 UI 女巫是我无法将属性类型更改为 BindingList 的原因。好吧,没关系。 BindingAdapter 有效。

标签: .net winforms data-binding


【解决方案1】:

您可能可以创建一个包含在您的类中的子类,该子类继承自可枚举并绑定到该类。有点像这样:

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

这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多