views:

147

answers:

2

Trivial data binding examples are just that, trivial. I want to do something a little more complicated and am wondering if there's an easy, built in way to handle it.

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
    List<DataStruct> list = new List<DataStruct>()
    {
      new DataStruct(){Name = "Name 1", Value = "Value 1", ComplexValue = new ComplexValue(){Part1 = "1:P1", Part2 = "1:P2"}},
      new DataStruct(){Name = "Name 2", Value = "Value 2", ComplexValue = new ComplexValue(){Part1 = "2:P1", Part2 = "2:P2"}}
    };

    listBox1.DataSource = list;
    listBox1.DisplayMember = "ComplexValue.Part1";
  }
}

public class DataStruct
{
  public string Name { get; set; }
  public string Value { get; set; }
  public ComplexValue ComplexValue { get; set; }
}

public class ComplexValue
{
  public string Part1 { get; set; }
  public string Part2 { get; set; }
}

Is there an easy way to get the value of the Part1 property to be set as the display member for a list of DataStruct items? Above I tried something that I thought made sense, but it just defaults back to the ToString() on DataStruct. I can work around it if necessary, I was just wondering if there was something built into the data binding that would handle more complex data binding like above.

Edit: Using WinForms

+2  A: 

perhaps not a built-in way, but you could always define

DataStruct {
    public ComplexValuePart1 { 
        get { return ComplexValue.Part1; }
    }
}

and set your DisplayMember to that

Jimmy
+2  A: 

Personally I'd go for a simple solution like Jimmy's - however, if you want to do this (with regular win-form bindings), you'd need to use a custom type descriptor to flatten Part1 / Part2 as virtual properties of DataStruct. You can do this via ICustomTypeDescriptor or TypeDescriptionProvider. The latter is more involved, but cleaner from a "separation of concerns" viewpoint.

If you really want I can prepare an example (or there are many I've done in the past floating around) - but simple is beautiful: if you only have a few properties, a simple facade (i.e. pass-thru properties on DataStruct) would be preferable.

Marc Gravell