views:

44

answers:

1

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

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.

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.

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 ? (can't post link, but that is the exact title)

A: 

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

This should do the trick.

Mark Synowiec