【问题标题】:Datagrid add data dynamicallyDatagrid动态添加数据
【发布时间】:2014-01-15 12:36:59
【问题描述】:

我是 WPF 新手并尝试在 DataGrid 中添加行作为数据,我尝试了以下代码,它添加了行但不显示行中的文本。

我有一个XElement array,我想从中循环foreach 并在DataGrid 中添加项目 成功添加后,有什么方法可以将ID 分配给DataGrid 的行,所以当我单击行时,我可以获得指定行的ID。请指导。

(编辑) XElement 数组包含 XML

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

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    不要使用代码将数据添加到数据网格,而是尝试将其与您拥有的数据源绑定。

    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 列,仅添加 Title 列。您必须为行实现 MouseDown 事件,并且在该行中您将找到该行的 DataContext,这将是您可以从中获取 ID 的数据项。

    【讨论】:

    • 抱歉没有清除,我已经更新了我的问题请检查。您的解决方案无法工作,因为我没有任何列名可以放入绑定构造函数中。我有 XML XElemets,我可以从中查询并放入网格
    • 您好,根据您的更新,我也更新了我的代码。您可以将 linq 与 XElement 数组一起使用来创建一个新的匿名对象集合,您可以将其与数据网格绑定。
    • 非常感谢,我不知道该怎么做。非常感谢。我可以将id 分配为tag 用于row 并且仅将title 分配为行的文本吗?所以当我单击该行时,我可以获得id 以供参考?
    • @Nithin Joshi 你能告诉我该怎么做吗,按照你的代码 plz
    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 2023-04-06
    • 1970-01-01
    • 2011-06-21
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多