【问题标题】:Populate WPF DataGrid with unknown amount of data from XML使用来自 XML 的未知数据量填充 WPF DataGrid
【发布时间】:2011-10-19 02:18:54
【问题描述】:

我正在尝试从 xml 文件中读取“数据”元素中的所有属性并将它们显示在 DataGrid(WPF、.Net 4.0)中

XML 格式如下所示。

<root>
  <Data Name1="Value1" Name2="Value2" ... />
  <Data Name1="Value1" Name2="Value2" ... />
  ...
</root>

我不知道使用的属性名称(例如 Name1、Name2、Foo 等)或每个元素中的属性数量(每个元素的属性数量可能不同)。每个新元素都应显示在新行上,每个属性对应一列(如果该行不存在则显示 null)。

我正在努力为要绑定的数据网格创建一个支持类,或者以编程方式创建它。

我目前的尝试是创建一组文本列(根据我从 xml 文件中提取的内容给出要使用的列名列表)

List<string> dataTags = ...; //get list of attributes to use from xml
foreach (string d in dataTags) {
    DataGridTextColumn col = new DataGridTextColumn();
    col.Header = d;
    dataGrid.Columns.Add(col);
}

然后,如果属性名称与标题值之一匹配,我将遍历每个属性并将其添加到列表中(以表示要在数据网格中显示的行)

foreach (XElement e in xml.Descendants("Data")) {
    //Store values to be added to the datagrid as a new row
    List<string> row = new List<string>();

    //Only add data where the attribute name matches one of the 'dataTags' we are given.
    foreach(string d in dataTags) {
        foreach (XAttribute a in e.Attributes()) {
            if (d.Equals(a.Name.ToString())) {
                row.Add(a.Value);
                break;
            }
        }
    }

    //Add new row to the datagrid
    dgData.Items.Add(row);
}

我在那儿有点……但是有一个带有空白行的数据网格(行数正确,但现在显示了数据)。

任何提示/指针将不胜感激。

【问题讨论】:

    标签: c# wpf xml datagrid


    【解决方案1】:

    那么您动态创建列的代码是正确的。

    但是您在数据网格中添加项目的代码不正确。为此,在您配置列时,将 XPATH 分配给它们。

      List<string> dataTags = ...; //get list of attributes to use from xml 
      foreach (string d in dataTags)
      {
             DataGridTextColumn col = new DataGridTextColumn();
             col.Binding = new Binding() { XPath = "@" + d } ;
             col.Header = d;
             dataGrid.Columns.Add(col);
      } 
    

    然后将您的 XmlNodes 作为 ItemsSource 分配给 datgrid...

      dataGrid.ItemsSource = xml.Descendants("Data");
    

    还有这篇文章使用XmlDataProvider

    【讨论】:

    • 谢谢...这会出现可怕的空行(即没有显示数据)。我可以确认 dataGrid.ItemsSource 设置为 XML 元素,并且列绑定是正确的 - 但仍然没有显示任何数据。
    • 我已经离开几天了。刚回来并尝试了 XmlDataProvider 解决方案。效果很好。感谢您朝正确的方向点头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2023-04-11
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多