How to bind xml to the WPF DataGrid correctly?

前提是你 提交于 2019-11-27 04:54:18

I used XLinq and worked fine, using a XElement instead of a XDocument :

XElement TrackList = XElement.Load("List.xml");
LibraryView.DataContext = TrackList;

Xaml:

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[track]}">
    <DataGrid.Columns>
         <DataGridTextColumn Header="Artist" Binding="{Binding Path=Element[artist_name].Value}"/>
         <DataGridTextColumn Header="Album" Binding="{Binding Path=Element[album_name].Value}"/>
         <DataGridTextColumn Header="Length" Binding="{Binding Path=Element[duration].Value}"/>
    </DataGrid.Columns>
</DataGrid>

Binding XPath is only relevant if you are binding to something that is an XmlNode (e.g. you are using XmlDataProvider). See here.

XPath does not work with XDocument classes. The only way to bind to properties of an XDocument is the normal Path syntax, which is not XML aware.

Your best bet is either to use the XmlDataSource, or convert your Xml document via XDocument into a POCO. That is pretty simple using LINQ:

XDocument doc = XDocument.Load(xmlFile);

            var tracks = from track in doc.Descendants("data") 
                    select new Track()
                               {
                                   Name= track.Element("name").Value,    
                                   Duration= track.Element("duration").Value,    
                                   etc ... 
                               };
LibraryView.ItemsSource = tracks;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!