简体   繁体   中英

How do I add columns and cells in a row to a datagrid programmatically?

I've got a method that excepts some object and gets every property of it using reflection. Property names are set to be column headers and are binded to the values that are supposed to be in cells under them. The headers are being displayed, but the values in cells are not. When I try to add a value to a datagrid, binding it to the perviously set column it doesn't appear in a table. Tell me, what I'm doing wrong here, please!

Here's an example of this method:

private void Output<T>(T obj)
    {
        foreach (var prop in obj.GetType().GetProperties())
        {
            var column = prop.Name;
            CarDetailsGrid.Columns.Add(new DataGridTextColumn()
            {
                Header = column,
                Binding = new Binding(column)
            });

            var value = prop.GetValue(obj);
            CarDetailsGrid.Items.Add(new { column = value != null ? value : "" });
        }
    }

There is a difference in adding rows and columns. Try doing the following:

private void Output<T>(List<T> objList)
{
    foreach (var prop in T.GetProperties())
    {
        var column = prop.Name;
        CarDetailsGrid.Columns.Add(new DataGridTextColumn()
        {
            Header = column,
            Binding = new Binding(column)
        });
    }

    if (objList != null && objList.Any())
    {
        foreach(var currObj in objList)
        {
            CarDetailsGrid.Items.Add(currObj);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM