0

我的组合框显示世界国家列表时遇到了一个奇怪的问题。我使用 XML (AllCountries.xml) 文件作为我的数据源:

<?xml version="1.0" encoding="utf-8"?>
<countries>
  <country>
    <iso>AF</iso>
    <name>Afghanistan</name>
  </country>
  <country>
    <iso>AL</iso>
    <name>Albania</name>
  </country>
  <country>
    <iso>DZ</iso>
    <name>Algeria</name>
  </country>
  <country>
    <iso>AS</iso>
    <name>American Samoa</name>
  </country>
  <country>
    <iso>AD</iso>
    <name>Andorra</name>
  </country> etc

我的组合框 XAML 如下所示:

<ComboBox 
      Width="200"
      SelectedValuePath="Country"
      ItemsSource="{Binding XPath=/countries/country/name}">
      <ComboBox.DataContext>
         <XmlDataProvider x:Name="Dataxml" Source="\Content\AllCountries.xml" />
      </ComboBox.DataContext>
</ComboBox>

一切都很好:我看到阿富汗、阿尔巴尼亚、阿尔及利亚 +++ 。好的,所以我希望在下拉列表中显示相关的(iso)代码,如下所示:

阿富汗,AF

阿尔巴尼亚, AL

阿尔及利亚,DZ

等等。为此,我将此 ItemTemplate 添加到我的组合框中:

<ComboBox.ItemTemplate>
     <DataTemplate>
          <TextBlock>
               <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0}, {1}">
                          <Binding XPath="/countries/country/name" />
                          <Binding XPath="/countries/country/iso" />
                    </MultiBinding>
                </TextBlock.Text>
          </TextBlock>
     </DataTemplate>
</ComboBox.ItemTemplate>

运行应用程序时,一切似乎都正常 - 直到我单击组合框并看到以下列表显示:

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF

阿富汗,AF....

:-( 我的 XPath 多重绑定显然有问题,但我无法弄清楚。这是怎么回事???

4

2 回答 2

2

这应该工作

ItemsSource="{Binding XPath=/countries/country}"

<MultiBinding StringFormat="{}{0}, {1}">
    <Binding XPath="name" />
    <Binding XPath="iso" />
</MultiBinding>

因为每个ComboBoxItem人都有一个国家作为DataContext

于 2013-06-30T14:49:58.180 回答
0

您也可以尝试设置ItemTemplateso以便在TextBlocks里面托管2个并与路径进行数据绑定!

<ComboBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding XPath="/countries/country/name" }" />
          <TextBlock Text="{Binding XPath="/countries/country/iso" }" />
        </DataTemplate>
      </ComboBox.ItemTemplate> 
</ComboBox>
于 2013-06-30T14:53:57.577 回答