繁体   English   中英

Datagrid动态添加数据

[英]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.

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