Binding to XML data in UWP

时间:2018-05-17 19:32:57

标签: c# xml data-binding uwp

There seems to be no way in UWP to bind to XML data. In WPF you can do this...

Define a resource...

<XmlDataProvider x:Key="SolarSystem" XPath="SolarSystem/Planets">
    <x:XData>
        <SolarSystem xmlns="">
            <Planets>
                <Planet Name="Mercury" Type="Terrestrial"/>
                <Planet Name="Venus" Type="Terrestrial"/>
                <Planet Name="Earth" Type="Terrestrial"/>
                <Planet Name="Mars" Type="Terrestrial"/>
                <Planet Name="Jupiter" Type="Giant"/>
                <Planet Name="Saturn" Type="Giant"/>
                <Planet Name="Uranus" Type="Giant"/>
                <Planet Name="Neptune" Type="Giant"/>
                <Planet Name="Ceres" Type="Dwarf"/>
                <Planet Name="Pluto" Type="Dwarf"/>
                <Planet Name="Haumea" Type="Dwarf"/>
                <Planet Name="Makemake" Type="Dwarf"/>
                <Planet Name="Eris" Type="Dwarf"/>
            </Planets>
        </SolarSystem>
    </x:XData>
</XmlDataProvider>

Bind XML to a ListView...

<ListView Name="ListView5" ItemsSource="{Binding Source={StaticResource SolarSystem},XPath=*}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding XPath=@Name}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Cannot seem to do anything remotely similar in UWP. I can put XML in a file, read it into an XmlDocument...still cannot bind to it. Cannot seem to bind to anything other than POCO. Surely I can bind to something other than C# objects. What am I missing?

1 个答案:

答案 0 :(得分:1)

我通常将数据放入数据表中,然后绑定到表

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;

namespace ConsoleApplication45
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Type", typeof(string));


            XDocument doc = XDocument.Load(FILENAME);
            foreach(XElement planet in doc.Descendants("Planet"))
            {
                dt.Rows.Add(new object[] {
                    (string)planet.Attribute("Name"),
                    (string)planet.Attribute("Type")
                });
            }
        }

    }
}