4

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:

Community
  • 1
  • 1
bigh_29
  • 2,529
  • 26
  • 22
  • Did you get any other solutions for that problem? I'm having this problem too and changing the property return value to BindingList is not possible. – Sebastian Schumann Oct 21 '14 at 10:19
  • I don't remember finding a good solution. I think I decided not to use databinding for objects of this type. – bigh_29 Jan 08 '15 at 16:04
  • Thx. I created an BindingAdapter that takes an ExpressionTree and contains only one Property do bind. The ExpressionTree supports mutch more that default binding of WinForms can do. I'm now able to bind a textedit to a specific item of a list and so on. I'm creating a dynamic UI witch was the reason why I can't change the property type to BindingList. Well, no matter. The BindingAdapter works. – Sebastian Schumann Jan 19 '15 at 07:58

1 Answers1

0

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
  • 5,385
  • 1
  • 22
  • 18