[英]Datagrid add data dynamically
我是WPF的新手,並嘗試將行添加為DataGrid
數據,我嘗試了以下代碼,它添加行但不顯示行中的文本。
我有一個XElement array
,我想從中循環foreach
並在DataGrid
添加項目。添加成功后,有任何方法可以將ID
分配給DataGrid
行,因此當我單擊row時,我可以獲得指定行的ID
。 請指導。
(編輯)包含XML的XElement數組
[0] => <objective id="1" title="obj 1"> </objective>
[1] => <objective id="2" title="obj 2"> </objective>
[2] => <objective id="3" title="obj 3"> </objective>
我嘗試的代碼在Grid中添加了空行:
var datagridTopic = new DataGrid {Width = 400, IsReadOnly = true};
//I only need one column
datagridTopic.Columns.Add(new DataGridTextColumn()
{
Header = "Topic",
Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
});
datagridTopic.Items.Add("obj 1");
datagridTopic.Items.Add("obj 2");
StackPanelContent.Children.Add(datagridTopic);
我想做的是:
foreach (var element in XElement)
{
string title = element.Attributes("title").ElementAt(0).Value; // obj 1
datagridTopic.Items.Add(title);
}
與其嘗試使用代碼將數據添加到數據網格,不如將其與您擁有的數據源綁定。
var datagridTopic = new DataGrid {Width = 400, IsReadOnly = true};
//I only need one column
var column1 = new DataGridTextColumn()
{
Header = "ID",
Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
};
column1.Binding = new Binding("ID")
datagridTopic.Columns.Add(column1);
var column2 = new DataGridTextColumn()
{
Header = "Title",
Width = datagridTopic.Width - 8 //after adding rows the grid gets scroll, so made column width lower
};
column2.Binding = new Binding("Title")
datagridTopic.Columns.Add(column2);
var items = xElementArray.Select(x => new { ID= x.Attribute("id").Value, Title = x.Attribute("title").Value});
datagridTopic.ItemsSource = items; //set the data source for the grid to custom created items.
StackPanelContent.Children.Add(datagridTopic);
如果不想在網格中顯示ID,則不要添加ID列,而僅添加標題列。 您將必須為這些行實現MouseDown事件,並在該行中找到該行的DataContext,這將是您的數據項,您可以從中獲取ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.