2012-08-13 62 views
0

我有以下XML文件:如何將兩個WPF組合框綁定到單個XML文件?

<Palettes> 
    <Palette> 
    <Primary Name="Black"/> 
    <Other Name="Blue"/> 
    <Other Name="Red"/> 
    </Palette> 
    <Palette> 
    <Primary Name="Green"/> 
    <Other Name="Orange"/> 
    <Other Name="Yellow"/> 
    <Other Name="Violet"/> 
    </Palette> 
</Palettes> 

我想有兩個組合框:一個用來顯示每個調色板的原色,和另一個其顯示在第一選擇的調色板的「其他」的顏色組合。

我想在XAML文件中完成此數據綁定,而不是在代碼隱藏中,如果可能的話。

我有以下XAML文件:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="80" Width="350"> 
    <Window.Resources> 
     <XmlDataProvider x:Key="Palettes" Source="pack://siteoforigin:,,,/Palettes.xml" /> 
    </Window.Resources> 
    <Grid> 
     <ComboBox x:Name="cbxPrimary" 
        DisplayMemberPath="Primary/@Name" 
        ItemsSource="{Binding Mode=OneWay, Source={StaticResource Palettes}, XPath=/Palettes/Palette}" 
        Margin="10,10,175,10" 
        SelectedIndex="0"/> 
     <ComboBox x:Name="cbxOther" 
        DisplayMemberPath="Other/@Name" 
        ItemsSource="{Binding ElementName=cbxPrimary, Mode=OneWay, Path=SelectedItem}" 
        Margin="175,10,10,10" 
        SelectedIndex="0" 
        SelectedValue="{Binding XPath=./Other/@Name}" 
        SelectedValuePath="./Other/@Name"/> 
    </Grid> 
</Window> 

然而,這將顯示空白條目在第二個組合框中的「其他」顏色:

Blank combo box

我想不出無論我是否錯過了某些東西,或者這是否編碼不正確。這怎麼可以糾正?

+1

你可以在這些綁定上放一個'OneWay','ItemsSource'幾乎總是單向的(你不能用一個簡單的'ComboBox'修改它) – 2012-08-13 20:16:52

回答

2

由於DisplayMemberPath的名稱意味着它是一個成員的路徑,而不是任意嵌套的節點或屬性。我想改變綁定如下:

<ComboBox x:Name="cbxOther" 
      DataContext="{Binding ElementName=cbxPrimary, Path=SelectedItem}" 
      ItemsSource="{Binding XPath=./Other/@Name}" 
      Margin="175,10,10,10" 
      SelectedIndex="0"/> 

使用SelectedValue/PathDisplayMemberPath纔有意義當顯示應當從基礎值不同。