2012-12-07 13 views
0

我有一個看起來像上的SelectionChanged更新標籤從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一個XML文件,Item 1價值和Item 2,以及兩行分別包含TextBoxLabel。是否可以將Label.Content屬性分別綁定到ListBox中所選項目的FirstPropertySecondProperty?上述代碼將一個Label綁定到所選項目的,該項目正常工作,但不是我想要顯示的值。我猜想我真正需要的是指定itemList的源代碼並找到與XPath匹配的值,但首先我不確定如何進行比較,其次我很想知道是否有更好的方法,假設有一個。

如果這是不可能的,我能想到的唯一解決方案是以編程方式在SelectionChanged事件處理程序中執行此操作。這會起作用,但我寧願不必分裂這樣的行爲。

回答

1

像這樣直接768,16做的伎倆,

綁定ItemsListBox和使用DisplayMemberpath顯示從Item節點所需的屬性。

然後通過設置LabelDataContextListBoxSelectedItem節點,您可以通過訪問XPathLabelContent

<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> 
所有屬性