数据绑定到一个对象的属性实现IEnumerable [英] Databinding to the properties of an object that implements IEnumerable

查看:128
本文介绍了数据绑定到一个对象的属性实现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");
}

这应该可以解决问题。

这篇关于数据绑定到一个对象的属性实现IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆