0

我有一个看起来像的 XML 文件

<Items>
    <Item>
        <Name>Item 1</Name>
        <FirstProperty>42</FirstProperty>
        <SecondProperty>37</SecondProperty>
    </Item>
    <Item>
        <Name>Item 2</Name>
        <FirstProperty>11</FirstProperty>
        <SecondProperty>35</SecondProperty>
    </Item>
</Items>

和一个看起来像的 XAML 文件

<Grid>
    <Grid.Resources>
        <XmlDataProvider x:Key="ItemsXml" XPath="Items/Item" Source="Items.xml"/>
    </Grid.Resources>
    <ListBox Name="itemList" HorizontalAlignment="Left"
                ItemsSource="{Binding Source={StaticResource ItemsXml}, XPath=//Name}"/>
    <TextBox HorizontalAlignment="Right" VerticalAlignment="Top" Margin="80,0" Width="30"/>
    <TextBox HorizontalAlignment="Right" VerticalAlignment="Top" Margin="80,50" Width="30"/>
    <Label HorizontalAlignment="Right" VerticalAlignment="Top"
           Content="{Binding ElementName=areaList, Path=SelectedValue}"/>
    <Label HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,50" Content="Bind me?"/>
</Grid>

这显示了ListBox包含两个元素的 aItem 1和,以及包含 a和 a 的Item 2两行。是否可以将属性分别绑定到中的选定项目?上面的代码将一个绑定到所选项目的,它可以正常工作,但那不是我想要显示的值。我猜我真正需要的是指定XPath 的来源并找到匹配值,但首先我不确定如何进行比较,其次我很想知道是否有更好的方法,假设有完全是一个。TextBoxLabelLabel.ContentFirstPropertySecondPropertyListBoxLabelitemList

如果这不可能,我能想到的唯一解决方案是在SelectionChanged事件处理程序中以编程方式进行。那会起作用,但我宁愿不必像那样拆分行为。

4

1 回答 1

1

像这样的东西应该可以解决问题,

Items将直接绑定到ListBox并用于DisplayMemberpathItem节点显示您想要的属性。

然后通过将 设置Label DataContext为节点,ListBox SelectedItem您可以通过XPathLabel Content

<Grid>
    <Grid.Resources>
        <XmlDataProvider x:Key="ItemsXml" XPath="Items/Item" Source="Items.xml" />
    </Grid.Resources>
    <ListBox Name="itemList" Width="172" 
             ItemsSource="{Binding Source={StaticResource ItemsXml}}"
             DisplayMemberPath="Name" Margin="0,0,570,0" />

    <Label DataContext="{Binding SelectedItem, ElementName=itemList}" 
           Content="{Binding XPath=FirstProperty}" Width="160" Height="30" Margin="178,48,403,233" />

    <Label DataContext="{Binding SelectedItem, ElementName=itemList}" 
           Content="{Binding XPath=SecondProperty}" Width="160" Height="30" Margin="178,12,403,269" />
</Grid>
于 2012-12-08T03:04:32.930 回答