在WPF DataGrid中动态生成列? [英] Generating columns dynamically in the WPF DataGrid?

查看:240
本文介绍了在WPF DataGrid中动态生成列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
  </DataGrid.Columns>
</DataGrid>

在上述代码片段中,DataGrid列在XAML中是硬编码的。

In the above snippet the DataGrid columns are hard coded in the XAML.

可以在MVVM View-Model中将列定义定义在其他位置,以便可以在列中定义和重新定义列?

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?

推荐答案

使用Microsoft DataGrid 与MVVM模式以以下方式适用于我,因为 DataGrid 根据 DataTable 自动生成列。

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.

在XAML中包括 DataGrid

<WpfToolkit:DataGrid 
    ItemsSource="{Binding Path=GridData, Mode=OneWay}" > 
</WpfToolkit:DataGrid> 

在我的视图模型中,我公开了一个 DataView

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; 
  } 
} 

这篇关于在WPF DataGrid中动态生成列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆