I am working with DataGrids but I am struggling to binding my data since the number of columns varies depending of the info that has to be showed.
So, what I have tried to do is to create and object which contains all the columns and rows that I need at some point and binding this object to the ItemsSource property. Since I have worked with DataGridViews in WindowsForms I have in mind something like this:
DataTable myTable = new DataTable();
DataColumn col01 = new DataColumn("col 01");
myTable.Columns.Add(col01);
DataColumn col02 = new DataColumn("col 02");
myTable.Columns.Add(col02);
DataRow row = myTable.NewRow();
row[0] = "data01";
row[1] = "data02";
myTable.Rows.Add(row);
row = myTable.NewRow();
row[0] = "data01";
row[1] = "data02";
myTable.Rows.Add(row);
But I haven’t been able to find a way to do the same thing in WPF since I need some columns to be DataGridComboBoxColumns for example.
Actually I have read many post about it in this site, but none of them helped to me. I am really lost.
Could anyone help me? I just need to be able to create a table which may contain DataGridTextColumns or `DataGridComboBoxColumns, etc, In order to bind this final object to the DataGrid’s ItemsSource property.
Hope someone can help me.
Okay, let me try to take an example which is similar to your needs
Let’s assume we use this class:
And we are willing to display a
DataGridlisting the ID, and having as a second column aButton, with the propertyMyStringas content, which, when clicked, launches theICommandMyCommandwhich opens in a new window whatever you want.Here is what you should have on the View side:
This will show a
DataGridtaking all the content in anIEnumerable<MyObject>named ‘MyList’, and shows two columns as defined before.Now if you need to define the command.
First, I recommend you read this introductory link to MVVM and take the
RelayCommandclass (that’s what we’re gonna use for your problem)So, in your
ViewModel, the one which defines theMyList, here is how you should define some of the useful objects: