wpf - 在 WPF DataGrid 中动态生成列?

标签 wpf datagrid

<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/

相关文章:

wpf - 有没有办法在 Storyboard中使用 setter 而不是动画?

c# - 命名空间中不存在控件

wpf - 拉伸(stretch)分离器不起作用

wpf - 无法在 Windows 8(WPF、.NET 4.0)下横向打印文档

c# - 如何使用DataGridComboBoxColumn?

apache-flex - 我如何知道何时单击了 Flex DataGrid itemRenderer 中的按钮?

c# - 对未知列使用特定的 DataTemplate

c# - 如何从 WPF 中的基类型集合中为子类型集合自动生成 DataGrid 列?

WPF 数据网格——行的编程选择似乎破坏了多选(特别是 shift-click 多选)

WPF ListView - 当控件准备好迭代呈现的项目时发生事件?