简体   繁体   中英

XAML DataBinding from code behind from XML source

Here's my XML

<?xml version="1.0" encoding="utf-8"?>
<app>
<films>
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
    <film name="Haha" year="2008" />
</films>
</app>

Here's my XAML

<ListBox x:Name="listBoxControl">
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <StackPanel>
                <TextBlock Text="{Binding Path=@name}" />
                <TextBlock Text="{Binding Path=@year}" />
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

and here's my C#

XDocument xmldoc = XDocument.Load(new StringReader(result));
listBoxControl.ItemsSource = xmldoc.Descendants("film");

For the past couple of hours, I've scoured the internet and Stack Overflow questions in hope for a solution. What I'm doing is, asynchronously downloading some XML data from my website, then passing it on to the ListBox control called "listBoxControl." The problem is the "Text" fields not rendering any text in them. I'm using "Path" inside Binding because XPath isn't allowed, I get this error: The property 'XPath' was not found in type 'Binding'

Now, what am I doing wrong here? It's a WP7.1 app in C# using Visual Studio Express for Windows Phone running on Windows 8 Consumer Preview.

I'd just make a class and bind to that:

public class Film
{
    public string name { get; set; }
    public string year { get; set; }
}

var d = xmldoc.Descendants("film").Select(x => new Film { name = x.Attribute("name").Value, year = x.Attribute("year").Value });

<TextBlock Text="{Binding name}" />
<TextBlock Text="{Binding year}" />

Edit: Or anonymous type:

var d = xmldoc.Descendants("film").Select(x => new { name = x.Attribute("name").Value, year = x.Attribute("year").Value });

<TextBlock Text="{Binding name}" />
<TextBlock Text="{Binding year}" />

Binding using XPath is not supported on Windows Phone.

So the only way to solve this is by deserializing the xml and binding to a .NET object.

Make sure, if you are going to allow the user to change the data or the refresh the data from the source that you implement INotifyPropertyChanged on the class so the UI gets notified of changes in the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM