<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
</DataGrid>
In the above snippet the DataGrid columns are hard coded in the XAML.
Is it possible to have the column definitions be defined elsewhere, ideally in the MVVM View-Model, so that the columns can be defined and redefined on the fly?
The post is devoted to the WPF data grid with dynamically defined number of rows and columns, but all cells have the same width and the same height. For example, such grid could be used in chess or checkers games for 8x8 field.
1. Creating DataGridColumn 2. Bind property At design time we are creating DataGridColumns like DataGridTextColumn using XAML like the following code. Now we will create the same thing using C# code. Use the namespace System.Windows.Controls in your window class if it is not used. Suppose my DataGrid name is "dgvRates" as in the following: 3.
Normally at design time when we create a DataGrid, we also create the required columns or set the autogenareted column property of the DataGrid to true to create automatically generate the columns based on the bound item source.
Autogenerates column headers and columns based on the Data model provided --> You can modify the DataGrid.Columns collection at run time regardless of whether it contains generated columns. However, if you specify columns in XAML, you should set AutoGenerateColumns to false in order to avoid duplication.
Using the Microsoft DataGrid
with the MVVM pattern in the following way works for me because the DataGrid
automatically generates the columns based on a DataTable
.
In XAML I include the DataGrid
:
<WpfToolkit:DataGrid
ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
</WpfToolkit:DataGrid>
In my view model I expose a DataView
:
public DataView GridData
{
get
{
DataSet ds = new DataSet("MyDataSet");
// everything hard-coded for this example
int to = 12;
int ps = 2048;
string sv = "10";
string st = "Open";
string wsid = "ZAMBONI";
DataTable dt = new DataTable("MyDataTable");
DataColumn propertyName = new DataColumn("Property");
DataColumn propertyValue = new DataColumn("Value");
dt.Columns.Add(propertyName);
dt.Columns.Add(propertyValue);
dt.Rows.Add("Connection timeout", to);
dt.Rows.Add("Packet size", ps);
dt.Rows.Add("Server version", sv);
dt.Rows.Add("State", st);
dt.Rows.Add("Worksation id", wsid);
ds.Tables.Add(dt);
return ds.Tables[0].DefaultView;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With