[英]How do you create columns programmatically in C# for a WPF toolkit datagrid?
[英]How to create N number of columns programmatically using C# with WPF DataGrid
我需要在 WPF DataGrid 中創建 N 列,其中每列的header = "i" (i = 1..N)
,然后向每列添加項目。 我在嘗試實現它時遇到了問題:
for (int i = 0; i < N; i++)
{
var col = new DataGridTextColumn();
col.Header = i.ToString();
col.Binding = new Binding(i.ToString());
dataGrid.Columns.Add(col);
dataGrid.Items.Add(new { i = "some txt" });
}
問題可能出在dataGrid.Items.Add(new { i = "some txt" });
我不知道如何解決它。 在這行代碼中,IDE 告訴i是一個匿名類型, i是一個數字而不是一個屬性。
在這種情況下,如何將項目添加到列中?
您可以創建一個 DataTable 並將您的列添加到 DataTable。 然后將該 DataTable 設置為數據網格視圖的數據源。
DataTable dt = new DataTable();
for(int i = 0; i < numberOfRows; i++){
DataRow row = dt.NewRow();
for(int c = 0; c < numberOfColumns; c++){
row[c] = "Your data here"
}
dt.Rows.Add(row);
}
MyDataGrid1.DataSource = dt;
綁定到索引應該有格式: [index]
。 您還應該在創建列后添加項目:
for (int i = 0; i < N; i++)
{
var col = new DataGridTextColumn
{
Header = i.ToString(),
Binding = new Binding("[" + i + "]"),
IsReadOnly = true,
Width = new DataGridLength(1, DataGridLengthUnitType.Star)
};
dataGrid.Columns.Add(col);
}
var rowData = Enumerable.Range(0, N).ToList();
dataGrid.Items.Add(rowData);
盡管我能夠類似地構建您的演示(使用 VS2017),但我認為它並不實用,因為它沒有顯示任何內容,因為您嘗試將綁定上下文設置為沒有特定類型的綁定源。
相反,這里有一些你可能會覺得有用的東西。 如果您有一個正在查詢或以其他方式填充的集合(List、ObservableCollection 等),並且您希望它自動構建,則可以使用反射來完成。 例如,我有一個自定義類
public class MySamplePerson
{
public string FirstName {get; set;}
public string LastName {get; set;}
public int Age {get; set;}
}
然后,在你的方法中,你准備了這些東西的清單
private void PrepareYourGrid()
{
// build a sample list of the data and I'm populating with 3 entries
var SampleData = new List<MySamplePerson>();
SampleData.Add(new MySamplePerson{ FirstName = "Bill", LastName = "Board", Age = 62});
SampleData.Add(new MySamplePerson{ FirstName = "Eileen", LastName = "Dover", Age = 32 });
SampleData.Add(new MySamplePerson{ FirstName = "Ben", LastName = "Dover", Age = 33});
// using reflection, I am taking the first instance within the list,
// getting the type, and then getting a list of all the properties on that class.
var pi = SampleData[0].GetType().GetProperties();
// Now, for each property, go through and create a column
foreach( var onePI in pi)
{
var col = new DataGridTextColumn();
// header based on the property name and binding to that same column name,
// not just some fixed "text" value you prove
col.Header = onePI.Name;
col.Binding = new Binding(onePI.Name);
// now add the column to the grid
MyDataGrid1.Columns.Add(col);
}
// Now I can set the ItemsSource for the grid to the list of records I created
MyDataGrid1.ItemsSource = SampleData;
}
在我的示例中,我的表單數據網格被命名為“MyDataGrid1”。 現在,如果您運行,網格將顯示與您擁有的行數一樣多的行,並且每個公共屬性也會公開..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.