如何动态地在C#中的XML绑定到一个WPF的DataGrid绑定、动态、DataGrid、XML

2023-09-04 01:18:05 作者:你不必弯腰因为我会踮脚

我环顾四周,这一点,但所有的例子我能找到使用XAML,这使得解决方案过于静态的。这是我想要做的:

I looked around for this, but all the examples I could find used XAML, which made the solution too static. Here is what I want to do:

我想填充DataGrid的行,列和要在运行时指定一个XML文件属性。一无所知DataGrid的属性可以是固定的;在XML驱使下来到最后的细节(所以为什么在XAML例子,我看到是不够的)。

I would like to populate a DataGrid's columns, rows and attributes from an XML file to be specified at run time. Nothing about the DataGrid's attributes can be fixed; the XML drives it down to the last detail (hence why the XAML examples I saw aren't sufficient).

XML文件的细节是公开的,所以任何布局都可以,但是作为一个例子:

The details of the XML file are open, so any layout will do, but as an example:

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

会产生一个名为两列的表格列和放大器;分别与价值观(歌罗西书1,100)及价值; (西2,200)的行1和; 2,分别

Would yield a grid of 2 columns named Column & Value respectively with the values ("Col 1", 100) & ("Col 2", 200) for the row 1 & 2, respectively.

再有,我有完全不同的XML没有问题的,所以我会采取什么样的工作。

Again, I have no problem with radically different XML, so I'll take what works.

这样的事情似乎非常有用,因为它允许创建通用数据可视组件在各种领域中。 XML将提供一个方便的通用格式传输结构化数据和DataGrid能提供丰富的视觉体验。

Something like this seems very useful as it would allow the creation of generic data viewing components in a variety of domains. XML would offer a convenient generic format for transmitting structured data and the DataGrid would offer a rich viewing experience.

推荐答案

感谢大家谁花时间阅读,或者我的要求作出回应。我想出如何做到这一点,我包括低于code片断:

Thank you to everyone who took the time to read or respond to my request. I figured out how to do this and am including a code snippet below:

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