简体   繁体   English

Datagrid动态添加数据

[英]Datagrid add data dynamically

I am new to WPF and trying to add rows as data in DataGrid , i tried the following code, it adds rows but do not show text in rows. 我是WPF的新手,并尝试将行添加为DataGrid数据,我尝试了以下代码,它添加行但不显示行中的文本。

I have an XElement array from which i want to loop foreach and add items in DataGrid And after successful addition is there any way to assign an ID to rows of DataGrid so when i click on row, i could get the ID for that rows specified. 我有一个XElement array ,我想从中循环foreach并在DataGrid添加项目。添加成功后,有任何方法可以将ID分配给DataGrid行,因此当我单击row时,我可以获得指定行的ID Please guide. 请指导。

(Edit) XElement Array Containing XML (编辑)包含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>

Code i tried, adds empty rows in Grid: 我尝试的代码在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);

What i want to do is: 我想做的是:

foreach (var element in XElement)
{
    string title = element.Attributes("title").ElementAt(0).Value; // obj 1
    datagridTopic.Items.Add(title);
}

Instead of adding data to the datagrid using code, try to bind it with the datasource you have. 与其尝试使用代码将数据添加到数据网格,不如将其与您拥有的数据源绑定。

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

If you don't want to display the ID in your grid, then don't add the ID column, add only Title column. 如果不想在网格中显示ID,则不要添加ID列,而仅添加标题列。 you will have to implement the MouseDown event for the rows and in that row you will find the DataContext of the row which will be your data item from which you can get the ID. 您将必须为这些行实现MouseDown事件,并在该行中找到该行的DataContext,这将是您的数据项,您可以从中获取ID。

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

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