<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
</DataGrid>
在上面的代码片段中,DataGrid 列在 XAML 中进行了硬编码。
是否可以在其他地方定义列定义,最好是在 MVVM View 模型中,以便可以动态定义和重新定义列?
最佳答案
使用 Microsoft DataGrid
以以下方式使用 MVVM 模式对我有用,因为 DataGrid
基于 DataTable
自动生成列.
在 XAML 中,我包含了 DataGrid
:
<WpfToolkit:DataGrid
ItemsSource="{Binding Path=GridData, Mode=OneWay}" >
</WpfToolkit:DataGrid>
在我的 View 模型中,我公开了一个
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;
}
}
关于wpf - 在 WPF DataGrid 中动态生成列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3564827/