xaml - 来自 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>
解决方案
下面的代码不会向文本块添加任何内容。我做错了什么。
问题是title
andcategory
是Element
书的而不是Attribute
。所以你需要像下面这样修改你的 linq
var newData = from query in loadedD.Descendants("element")
select new Book
{
Title = (string)query.Element("title"),
Category = (string)query.Element("category")
};
推荐阅读
- mysql - Discord.js 中的节点 mysql 返回空结果/数组
- sql - 具有多个(相同ID不同日期和不同图像)的SQL服务器查询(按最后日期过滤)
- kotlin - XMLPullParser 只返回一个元素
- multithreading - 为什么 Rust 会阻止多个可变引用?
- linux - 绕过 Xserver 显示管理
- methods - 在 Julia 中运行 Union 类型
- operating-system - 进程/线程可以在中断被禁用时运行吗?
- javascript - 来自猫鼬日期戳的JS日期格式
- sparql - 如何在 SPARQL 中访问 Colspan 表?
- sql - 在插入和删除操作后触发更新值?