【问题标题】:How to Dynamically Bind XML to a WPF DataGrid in C#如何在 C# 中将 XML 动态绑定到 WPF DataGrid
【发布时间】:2010-10-20 15:41:57
【问题描述】:

我四处寻找,但我能找到的所有示例都使用 XAML,这使得解决方案过于静态。这是我想做的:

我想从要在运行时指定的 XML 文件中填充 DataGrid 的列、行和属性。 DataGrid 的任何属性都无法修复; XML 将其推到最后一个细节(因此我看到的 XAML 示例还不够)。

XML 文件的详细信息是开放的,所以任何布局都可以,但作为示例:

<data>
    <row Column="Col 1" Value="100" />
    <row Column="Col 2" Value ="200" />
</data>

将生成一个包含 2 列的网格,分别命名为 Column & Value,其中第 1 行和第 2 行的值分别为 ("Col 1", 100) 和 ("Col 2", 200)。

再一次,我对完全不同的 XML 没有任何问题,所以我会选择可行的。

这样的东西似乎非常有用,因为它允许在各种域中创建通用数据查看组件。 XML 将为传输结构化数据提供一种方便的通用格式,而 DataGrid 将提供丰富的查看体验。

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    感谢所有花时间阅读或回复我的请求的人。我想出了如何做到这一点,并在下面包含了一个代码 sn-p:

    using System.Xml.Linq;    // Required for XElement...
    using System.Collections; // Required for Hashtable
    
    private void InitGridFromXML(string xmlPath)
    {
        var data = XElement.Load(xmlPath);
    
        // Set Grid data to row nodes (NOTE: grid = DataGrid member)
        var elements = data.Elements("row");
        grid.ItemsSource = elements;
    
        // Create grid columns from node attributes.  A hashtable ensures
        // only one column per attribute since this iterates through all
        // attributes in all nodes.  This way, the grid can handle nodes with
        // mutually different attribute sets.
        var cols = new Hashtable();
        foreach (var attr in elements.Attributes())
        {
            var col = attr.Name.LocalName;
    
            // Only add col if it wasn't added before
            if (!cols.Contains(col))
            {
                // Mark col as added
                cols[col] = true;
    
                // Add a column with the title of the attribute and bind to its
                // value
                grid.Columns.Add(new DataGridTextColumn
                {
                    Header = col,
                    Binding = new Binding("Attribute[" + col + "].Value")
                });
            }
        }
    }
    

    【讨论】:

    • 我喜欢这个,感谢发布。我调整了它的属性,但效果很好。
    【解决方案2】:

    您可以将 XML 序列化到一个集合并绑定该集合。

    您可以从 XML 创建数据表并将其绑定到数据网格。

    只要您有主详细格式的数据,您将其放入何种结构都没有关系。

    XML 如果你喜欢,

    以行和列的形式呈现数据。

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 2017-10-13
      • 2011-03-14
      • 2011-01-13
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多