2

I want to bind the following XML to a couple of controls in WPF.

Each category name should bind to the items source of a combo box, then when a category is selected in the combo box I want to bind the list of Products from the selected category to a listview

Here is the 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>

and so on..

1 Answer 1

2

Put your xml into a file called Categories.xml, and this should work...

<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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ian, Nice and simple...!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.