2012-07-14 41 views
0

我有两个组合框,我想根据第一个组合框的值更新第二个组合框。 我必须将组合框与xml文件绑定,而不是数据集。 我有搜索网,但没有找到有用的。从后面的代码绑定组合框与xml

在此先感谢您的帮助。

回答

0

尝试类似的东西:

XAML文件:

<Window x:Class="ComboBoxBindingXML.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <XmlDataProvider x:Key="myData"> 
      <x:XData xmlns=""> 
       <Books> 
        <Book Title="Book1"> 
         <Authors> 
          <Author Name="Make" Surname="Vey" /> 
          <Author Name="Jane" Surname="McRoy" /> 
         </Authors> 
        </Book> 
        <Book Title="Book2" /> 
        <Book Title="Book3" /> 
        <Book Title="Book4"> 
         <Authors> 
          <Author Name="John" Surname="Rat" /> 
          <Author Name="Dorian" Surname="Trust" /> 
         </Authors> 
        </Book> 
        <Book Title="Book5" /> 
       </Books> 
      </x:XData> 
     </XmlDataProvider> 
    </Window.Resources> 

    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="30" /> 
      <RowDefinition Height="10" /> 
      <RowDefinition Height="30" /> 
      <RowDefinition Height="10" /> 
      <RowDefinition Height="30" /> 
      <RowDefinition Height="10" /> 
      <RowDefinition Height="30" /> 
     </Grid.RowDefinitions> 

     <ComboBox Name="cbFirst" DataContext="{StaticResource myData}" ItemsSource="{Binding XPath=Books/Book }"> 
      <ComboBox.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding [email protected]}" FontWeight="Bold" /> 
       </DataTemplate> 
      </ComboBox.ItemTemplate> 
     </ComboBox> 

     <ComboBox Name="cbSecond" Grid.Row="2" DataContext="{Binding ElementName=cbFirst, Path=SelectedItem}" ItemsSource="{Binding XPath=Authors/Author}"> 
      <ComboBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Text="{Binding [email protected]}" FontWeight="Bold" /> 
         <TextBlock Text=" " /> 
         <TextBlock Text="{Binding [email protected]}" />       
        </StackPanel> 
       </DataTemplate> 
      </ComboBox.ItemTemplate> 
     </ComboBox> 

     <TextBlock Grid.Row="4" Text="{Binding ElementName=cbFirst, Path=Items.Count, UpdateSourceTrigger=PropertyChanged}" /> 
     <TextBlock Grid.Row="6" Text="{Binding ElementName=cbSecond, Path=Items.Count, UpdateSourceTrigger=PropertyChanged}" /> 
    </Grid> 
</Window> 

代码隐藏文件是空的。一切都发生在XAML文件中。

XmlDataProvider有属性“源”,您可以在其中设置XML数据文件的Uri。