简体   繁体   English

如何以编程方式设置模板并填充WPF DataGrid的内容?

[英]How to set template and fill content of WPF DataGrid programmatically?

I need to fill WPF DataGrid from DataTable programmatically. 我需要以编程方式从DataTable填充WPF DataGrid。 List of columns is not know in design time. 在设计时不知道列列表。

Columns should be generated manually (AutoGeneratingColumn event?) based on simple template having single Label. 列应基于具有单个Label的简单模板手动生成(AutoGeneratingColumn事件?)。 Label.Content is column name. Label.Content是列名。 Now binding allowed - template can be created in XAML but everything else need to be in C# 现在允许绑定-模板可以在XAML中创建,但其他所有内容都必须在C#中

A little bit complex approach is for rows. 行有点复杂的方法。 Data cell template should have single Label or TextBox but cell template should be set in runtime. 数据单元格模板应具有单个Label或TextBox,但应在运行时设置单元格模板。 For instance, string should be represented in cell is longer that 5 chars, then Label-based template should be used. 例如,字符串应在大于5个字符的单元格中表示,然后应使用基于标签的模板。 Otherwise, TextBox template should be used. 否则,应使用TextBox模板。 Again, templates only can be created in XAML. 同样,只能在XAML中创建模板。 Filling data need to be done in C# 填充数据需要在C#中完成

Here's some code to start with in order to generate data: 这是为了生成数据而开始的一些代码:

DataTable myTable = new DataTable(tableName);
myTable.Columns.Add(new DataColumn("id", typeof(int)));  
myTable.Columns.Add(new DataColumn("name", typeof(string)));
myTable.Rows.Add(new object[] {1, "label"});   
myTable.Rows.Add(new object[] {2, "text box"});

You can add the columns in the datagrid programatically by defining DataGridTextColumn and set its width, header and Binding. 您可以通过定义DataGridTextColumn并设置其宽度,标题和Binding,以编程方式在datagrid中添加列。

Here is a little example to get you the idea 这是一个让您明白的小例子

DataGridTextColumn column1 = new DataGridTextColumn();
column1.Header = myTable.Columns[0].Caption;
column1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
column1.Binding = new Binding("column1_name");

DataGridTextColumn column1 = new DataGridTextColumn();
column1.Header = myTable.Columns[1].Caption;
column1.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
column1.Binding = new Binding("column2_name");

dataGrid.Columns.Add(column1);
dataGrid.Columns.Add(column2);

Using this way you can define multiple columns in datagrid without knowing the no.of Columns at design time 使用这种方法,您可以在数据网格中定义多个列,而无需在设计时知道列数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM