0

I'm trying to add items to a DataGrid, unlike when I have used x.Items.Add(x); for a ListView it only shows blank rows. This DataGrid will only show 1 row at a time and must be editable, if you think there is a better approach rather than a DataGrid then I am open to suggestions. I've made sure the number of values matches the number of columns which was an issue to start with but it seems I am still no closer to solving this. I've tried reading many similar questions but none has solved my issue, where am I going wrong with this?

rw_container is a blank Grid I am using to insert the DataGrid into

private void AddGrid<T>(T obj) where T : ICategory
    {
        data = new DataGrid();

        PropertyInfo[] props = typeof(T).GetProperties();

        foreach (PropertyInfo x in props)
        {
            data.Columns.Add(new DataGridTextColumn() { Header = x.Name, Width = 100 });
        }


        //How to add the rows here?


        rw_container.Children.Add(data);
    }

1 Answers1

1

a couple of things are missing:

DataGridColumns need Binding to properties:

new DataGridTextColumn { Header = x.Name, Width = 100, Binding = new Binding(x.Name) }

and DataGrid needs items:

data.Items.Add(obj);

however, much simple approach is to set ItemsSource and let Datagrid auto-generate columns:

{
    data = new DataGrid { ItemsSource = new[] { obj } };

    rw_container.Children.Add(data);
}

this way DataGrid will even create DataGridCheckBoxColumns for bool properties

ASh
  • 34,632
  • 9
  • 60
  • 82
  • Thanks for the response, when I am able to test this I'll respond/mark this as the solution accordingly. –  Jan 28 '18 at 15:30