ghost_mv
ghost_mv

Reputation: 1200

Silverlight grid programmatic "complex property" databinding?

I have a datagrid that I'm building the contents of programmatically as the columns will change based on the complex collection property of the object. The object in question has say 2 standard properties.

public class MyObject
{
   private List<MyNameValuePairProps> props = new List<MyNameValuePairProps>();

   public int Id { get; set; }
   public string Name { get; set; }
   public List<MyNameValuePairProps> Props
   {
      get { return props; }
      set { props = value; }
   }
}

And programmatically I'm adding DataGridTextColumns per property like so:

DataGridTextColumn colId = new DataGridTextColumn();
colId.Header = "Id";
colId.Binding = new Binding("Id");
myDataGrid.Columns.Add(colId);

DataGridTextColumn colName = new DataGridTextColumn();
colName.Header = "Name";
colName.Binding = new Binding("Name");
myDataGrid.Columns.Add(colName);

How would I go about programmatically adding a column per "MyNameValuePairProp" in the "Props" list property of my object AND databind to that when I call this after I set up the columns:

myDataGrid.ItemsSource = myCollOfMyObjects;

Upvotes: 0

Views: 586

Answers (1)

Kir
Kir

Reputation: 3052

You can simply set the source on the binding (as below)

foreach(MyNameValuePairProps pair in Props)
{
    DataGridTextColumn column = x;// create column as you will
    column.Binding = new Binding("Value") { Source = pair};
    myDataGrid.Columns.Add(column);
}

Upvotes: 1

Related Questions