How to Dynamically Bind XML to a WPF DataGrid in C#

前端 未结 2 762
一生所求
一生所求 2021-01-23 18:36

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:

I would like to populate a DataGri

相关标签:
2条回答
  • 2021-01-23 18:54

    You could serialize the XML to a collection and bind that collection.

    You could create a data table from your XML and bind that to the datagrid.

    As long as you have data in master detail format it doesn't matter what structure you put it in.

    The XML if you make like,

    presents the data in rows and there columns values.

    0 讨论(0)
  • 2021-01-23 19:02

    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")
                });
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题