在 WPF 中使用 XML 属性作为列表源
我需要能够使用一系列属性作为 WPF 列表视图中的源。我目前陷入了如何做到这一点的困境。我知道如何对 XML 节点执行此操作,但不知道如何对属性执行此操作。这是我也尝试绑定的示例:
<Stats HP="55000" MP="2500" SP="2500" Strength="212" Vitality="125" Magic="200" Spirit="162" Skill="111" Speed="109" Evasion="100" MgEvasion="100" Accuracy="100" Luck="55" />
我希望每个统计名称/值都是列表视图中的一个条目。下面是我一直在尝试实现的代码:
<TabControl.DataContext>
<Binding ElementName="EnemyLevelsListBox" Path="SelectedItem"/>
</TabControl.DataContext>
<TabItem Header="Stats" Name="EnemyStatsTab">
<ListView ItemsSource="{Binding XPath=Stats}" Height="310" Name="EnemyStatViewDisplay" Width="411" HorizontalAlignment="Left">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Attribute.Name}" />
<TextBlock Text="{Binding Path=Attribute.Value}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</TabItem>
TabControl.DataContext 绑定公开了 Stats 元素的父 XMLNode。我肯定知道这一点,因为我在其他地方使用父节点的子节点并且它们工作正常。我不知道要为 ListView ItemsSource 或 DataTemplate 的文本块绑定放置什么。有人知道该怎么做吗?
I need to be able to use a series of attributes as the source in a WPF list view. I'm currently stuck on how to do this. I know how to do it for XML nodes but not for attributes. Here's an example of what I'm trying to bind too:
<Stats HP="55000" MP="2500" SP="2500" Strength="212" Vitality="125" Magic="200" Spirit="162" Skill="111" Speed="109" Evasion="100" MgEvasion="100" Accuracy="100" Luck="55" />
I want each stat name/value to be an entry in the listview. Here's the code I've been trying to make work:
<TabControl.DataContext>
<Binding ElementName="EnemyLevelsListBox" Path="SelectedItem"/>
</TabControl.DataContext>
<TabItem Header="Stats" Name="EnemyStatsTab">
<ListView ItemsSource="{Binding XPath=Stats}" Height="310" Name="EnemyStatViewDisplay" Width="411" HorizontalAlignment="Left">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Attribute.Name}" />
<TextBlock Text="{Binding Path=Attribute.Value}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</TabItem>
The TabControl.DataContext binding exposes the parent XMLNode of the Stats element. I know this for certain as I'm using subnodes of the parent elsewhere and they work correctly. I don't know what to put for the ListView ItemsSource or for the DataTemplate's textblock binds. Does someone know how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应在
ItemsSource
绑定中使用XPath
,因为您希望定位Attributes
集合位于XmlNode
对象。您应该确保您已经将Stats
元素作为DataContext
,然后将Path
设置为Attributes
:You should not use
XPath
in theItemsSource
binding as you want to target theAttributes
collection on theXmlNode
object. You should make sure you are already having theStats
element asDataContext
, then set thePath
toAttributes
:为什么不直接将列表视图绑定到属性呢?
XAML:
隐藏代码:
Why not just bind the listview to the attributes?
XAML:
Code behind: