Fill datagrid or listview from XML file

倾然丶 夕夏残阳落幕 提交于 2019-12-08 08:10:50

问题


I have a well formed XML file I would like to fill a datagrid with. I would prefer using the AutoGenerate feature of WFPToolKit datagrid, but could hard code the columns in.

The trouble I am having is getting the xml file contents into a datagrid. I had it partially working in a listview, but think a datagrid would be more suited for my needs.

Can anyone provide a quick example of how to accomplish this?


回答1:


I bound the XML to the ListView like this:

// Bind the data to the ListView
var binding = new System.Windows.Data.Binding() {  
  Source = MergedXmlDataProvider,  
  UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,  
  XPath = "//element" };  
this.listView1.SetBinding(ItemsControl.ItemsSourceProperty, binding);   

XML looks something like this:

<root>  
    <element location="here" state="now"/>  
    <element location="there" state="then"/>  
</root> 



回答2:


Aha! I finally worked it out with the help of another post here. Here is what I was able to get working, adding each XML element to a list view.

XDocument xdoc = XDocument.Load("c:\\isbn.xml");
var items = from item in xdoc.Descendants("BookData")
            select new
            {
                Title = item.Element("Title").Value,
                AuthTexts = item.Element("AuthorsText").Value
            };

foreach (var item in items)
{
    listView1.Items.Add(new { Title = item.Title, Author = item.AuthTexts });
}


来源:https://stackoverflow.com/questions/1383817/fill-datagrid-or-listview-from-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!