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

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.

Up vote 24 down vote favorite 12 share g+ share fb share tw.

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 to apply formatting. A simplified version of the output might be something like: class Data { IList ColumnDescriptions { get; set; } string Rows { get; set; } } This class is set as the DataContext on a WPF DataGrid but I actually create the columns programmatically: for (int I = 0; I ColumnDescriptions.

Count; i++) { dataGrid.Columns. Add(new DataGridTextColumn { Header = data. ColumnDescriptionsi.

Name, Binding = new Binding(string. Format("{0}", i)) }); } Is there any way to replace this code with data bindings in the XAML file instead? Wpf data-binding xaml datagrid link|improve this question asked Nov 26 '08 at 8:52Generic Error1,4723918 92% accept rate.

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).

– Phil Gan Feb 2 '11 at 16:26 1 The highest voted and accepted solution is not the best one! Two years later the answer would be: msmvps.com/blogs/deborahk/archive/2011/0... – Mikhail Apr 18 '11 at 18:08 2 No, It would not. Not the provided link anyway, because the result of that solution is completely different!

– 321X Aug 10 '11 at 19:59 Seems like Mealek's solution is much more universal, and is useful in situations where direct use of C# code is problematic, e.g. In ControlTemplates. – EFraim Dec 7 '11 at 18:59.

Here's a workaround for Binding Columns in the DataGrid. Since the Columns property is ReadOnly, like everyone noticed, I made an Attached Property called BindableColumns which updates the Columns in the DataGrid everytime the collection changes through the CollectionChanged event. If we have this Collection of DataGridColumn's public ObservableCollection ColumnCollection { get; private set; } Then we can bind BindableColumns to the ColumnCollection like this The Attached Property BindableColumns public class DataGridColumnsBehavior { public static readonly DependencyProperty BindableColumnsProperty = DependencyProperty.

RegisterAttached("BindableColumns", typeof(ObservableCollection), typeof(DataGridColumnsBehavior), new UIPropertyMetadata(null, BindableColumnsPropertyChanged)); private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { DataGrid dataGrid = source as DataGrid; ObservableCollection columns = e. NewValue as ObservableCollection; dataGrid.Columns.Clear(); if (columns == null) { return; } foreach (DataGridColumn column in columns) { dataGrid.Columns. Add(column); } columns.

CollectionChanged += (sender, e2) => { NotifyCollectionChangedEventArgs ne = e2 as NotifyCollectionChangedEventArgs; if (ne. Action == NotifyCollectionChangedAction. Reset) { dataGrid.Columns.Clear(); foreach (DataGridColumn column in ne.

NewItems) { dataGrid.Columns. Add(column); } } else if (ne. Action == NotifyCollectionChangedAction.

Add) { foreach (DataGridColumn column in ne. NewItems) { dataGrid.Columns. Add(column); } } else if (ne.

Action == NotifyCollectionChangedAction. Move) { dataGrid.Columns. Move(ne.

OldStartingIndex, ne. NewStartingIndex); } else if (ne. Action == NotifyCollectionChangedAction.

Remove) { foreach (DataGridColumn column in ne. OldItems) { dataGrid.Columns. Remove(column); } } else if (ne.

Action == NotifyCollectionChangedAction. Replace) { dataGrid.Columnsne. NewStartingIndex = ne.

NewItems0 as DataGridColumn; } }; } public static void SetBindableColumns(DependencyObject element, ObservableCollection value) { element. SetValue(BindableColumnsProperty, value); } public static ObservableCollection GetBindableColumns(DependencyObject element) { return (ObservableCollection)element. GetValue(BindableColumnsProperty); } }.

You can create a usercontrol with the grid definition and define 'child' controls with varied column definitions in xaml. The parent needs a dependency property for columns and a method for loading the columns: Parent: public ObservableCollection gridColumns { get { return (ObservableCollection)GetValue(ColumnsProperty); } set { SetValue(ColumnsProperty, value); } } public static readonly DependencyProperty ColumnsProperty = DependencyProperty. Register("gridColumns", typeof(ObservableCollection), typeof(parentControl), new PropertyMetadata(new ObservableCollection())); public void LoadGrid() { if (gridColumns.

Count > 0) myGrid.Columns.Clear(); foreach (DataGridColumn c in gridColumns) { myGrid.Columns. Add(c); } } Child Xaml: And finally, the tricky part is finding where to call 'LoadGrid'. I am struggling with this but got things to work by calling after InitalizeComponent in my window constructor (childGrid is x:name in window.

Xaml): childGrid.deGrid.LoadGrid(); Related blog entry.

I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid: Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM Basically, she creates a DataGridTemplateColumn and puts ItemsControl inside that displays multiple columns.

It works perfectly for both Silverlight and WPF! – Mikhail Apr 18 '11 at 18:02 It's by far not the same result as the programmed version! – 321X Aug 10 '11 at 19:58.

I managed to make it possible to dynamically add a column using just a line of code like this: MyItemsCollection. AddPropertyDescriptor( new DynamicPropertyDescriptor("Age", x => x. Age)); Regarding to the question, this is not a XAML-based solution (since as mentioned there is no reasonable way to do it), neither it is a solution which would operate directly with DataGrid.Columns.

It actually operates with DataGrid bound ItemsSource, which implements ITypedList and as such provides custom methods for PropertyDescriptor retrieval. In one place in code you can define "data rows" and "data columns" for your grid. If you would have: IList ColumnNames { get; set; } //dict.

Key is column name, dict. Value is value Dictionary Rows { get; set; } you could use for example: var descriptors= new List(); //retrieve column name from preprepared list or retrieve from one of the items in dictionary foreach(var columnName in ColumnNames) descriptors. Add(new DynamicPropertyDescriptor(ColumnName, x => xcolumnName)) MyItemsCollection = new DynamicDataGridSource(Rows, descriptors) and your grid using binding to MyItemsCollection would be populated with corresponding columns.

Those columns can be modified (new added or existing removed) at runtime dynamically and grid will automatically refresh it's columns collection. DynamicPropertyDescriptor mentioned above is just an upgrade to regular PropertyDescriptor and provides strongly-typed columns definition with some additional options. DynamicDataGridSource would otherwise work just fine event with basic PropertyDescriptor.

But there is much more to this, so I won't write it all down here, you can read more about dynamically adding columns to a datagrid using property descriptors on my blog.

You might be able to do this with AutoGenerateColumns and a DataTemplate. I'm not positive if it would work without a lot of work, you would have to play around with it. Honestly if you have a working solution already I wouldn't make the change just yet unless there's a big reason.

The DataGrid control is getting very good but it still needs some work (and I have a lot of learning left to do) to be able to do dynamic tasks like this easily.

My reason is that coming from ASP. Net I'm new to what can be done with decent data binding and I'm not sure where it's limits are. I'll have a play with AutoGenerateColumns, thanks.

– Generic Error Nov 26 '08 at 20:37.

Here's a workaround for Binding Columns in the DataGrid. Since the Columns property is ReadOnly, like everyone noticed, I made an Attached Property called BindableColumns which updates the Columns in the DataGrid everytime the collection changes through the CollectionChanged event.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions