How do I bind a WPF DataGrid to a variable number of columns?

后端 未结 8 1552
逝去的感伤
逝去的感伤 2020-11-22 10:29

My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used t

8条回答
  •  猫巷女王i
    2020-11-22 10:53

    I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.

    Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.

    Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:

    public static void GenerateColumns(this DataGrid dataGrid, IEnumerable columns)
    {
        dataGrid.Columns.Clear();
    
        int index = 0;
        foreach (var column in columns)
        {
            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = column.Name,
                Binding = new Binding(string.Format("[{0}]", index++))
            });
        }
    }
    
    // E.g. myGrid.GenerateColumns(schema);
    

提交回复
热议问题