我四处寻找这一点,但我能找到的所有示例都使用了 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 将提供丰富的查看体验。
感谢所有花时间阅读或回复我的请求的人。我想出了如何做到这一点,并在下面添加了一个代码片段:
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")
});
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)