Reputation: 2263
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..
Upvotes: 2
Views: 1106
Reputation: 7709
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>
Upvotes: 2