WPF绑定XML列表

时间:2009-12-09 21:41:14

标签: wpf xml data-binding binding

我想将以下XML绑定到WPF中的几个控件。

每个类别名称应绑定到组合框的项目源,然后在组合框中选择类别时,我想将所选类别中的产品列表绑定到列表视图

这是XML:

<?xml version="1.0" encoding="utf-8" ?>
<Categories>
  <Category Name="Category1">
    <Products>
      <Product Name="Product 1"/>
      <Product Name="Product 2"/>
    </Products>
  </Category>
  <Category Name="Category2">
    <Products>
      <Product Name="Product 1"/>
      <Product Name="Product 2"/>
      <Product Name="Product 3"/>
    </Products>
  </Category>
</Categories>

依旧......

1 个答案:

答案 0 :(得分:2)

将您的xml放入名为Categories.xml的文件中,这应该可以...

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <DataTemplate x:Key="categoryTemplate" DataType="Category">
            <TextBlock Text="{Binding XPath=@Name}" />
        </DataTemplate>
        <DataTemplate x:Key="productTemplate" DataType="Product">
            <TextBlock Text="{Binding XPath=@Name}" />
        </DataTemplate>
    </Grid.Resources>

    <Grid.DataContext>
        <XmlDataProvider
            Source="Categories.xml" XPath="/Categories/Category" />
    </Grid.DataContext>

    <ComboBox
        x:Name="categoryComboBox"
        Grid.Row="0" Margin="8"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}" ItemTemplate="{StaticResource categoryTemplate}" />

    <ListView
        Grid.Row="1" Margin="8"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding XPath=Products/Product}" ItemTemplate="{StaticResource productTemplate}" />
</Grid>