首页 > 解决方案 > 来自 XML 文件的数据绑定 [UWP]

问题描述

我有一些数据的 xml 文件,我想将它绑定到文本块。下面的代码不会向文本块添加任何内容。我做错了什么。有什么建议吗?

XAML:

<GridView x:Name="DataGrid1">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <Grid  Background="AliceBlue" Width="300" Height="200">
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding Title}"></TextBlock>
                            <TextBlock Text="{Binding Category}"></TextBlock>
                        </StackPanel>
                    </Grid>
                   </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>

C#

string XMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "booksData/data.xml");
            XDocument loadedD = XDocument.Load(XMLPath);

            var newData = from query in loadedD.Descendants("element")
                          select new Book
                          {
                              Title = (string)query.Attribute("title"),
                              Category = (string)query.Attribute("category")

                          };
            DataGrid1.ItemsSource = newData;

XML:

<books>
    <element>
      <category>Thriller</category>
      <description>In The Green Line, </description>
      <id>1</id>
      <image>images/greenLine.jpg</image>
      <price>10.50</price>
      <title>The Green Line</title>
    </element>

标签: xamluwpbinding

解决方案


下面的代码不会向文本块添加任何内容。我做错了什么。

问题titleandcategoryElement书的而不是Attribute。所以你需要像下面这样修改你的 linq

var newData = from query in loadedD.Descendants("element")
select new Book
{
  Title = (string)query.Element("title"),
   Category = (string)query.Element("category")    
};

推荐阅读