How to bind xml to the WPF DataGrid correctly?

前端 未结 2 1698
你的背包
你的背包 2020-11-30 10:42

I have looked for and tried various solutions but so far none of them solve my problem. I am using the built-in DataGrid from WPF in Visual Studio 2010/.NET4 to display data

相关标签:
2条回答
  • 2020-11-30 11:06

    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>
    
    0 讨论(0)
  • 2020-11-30 11:26

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