I have an XML file with the following structure:
<Products>
<Product name="MyProduct1">
<Components>
<Component name="MyComponent1">
<SubComponents>
<SubComponent name="MySubComponent1"/>
<SubComponent name="MySubComponent2"/>
...more SubComponent nodes...
</SubComponents>
</Component>
...more Component nodes...
</Components>
</Product>
...more Product nodes...
</Products>
I'm trying to create a WPF app that has a ComboBox with the Product names in it. I am completely new to WPF so I don't know if I'm going about things the right way. When a Product is chosen, a second ComboBox should be populated with all the Components for that Product. And when a Component is chosen, a third ComboBox should be populated with all the SubComponents for that Component.
I don't know how to set up a dependency between ComboBoxes except to populate the dependent ComboBox inside an event handler triggered by the independent ComboBox. This seems to imply I need to be able to read the XML in C#, so I have [Serializable]
classes for Products
, Product
, Component
, and SubComponent
. However, I was trying to do XML databinding in my XAML:
<Window.Resources>
<XmlDataProvider Source="Products.xml"
XPath="Products/Product"
x:Key="productsXml"/>
</Window.Resources>
I'm currently not seeing a list of Product names in my first ComboBox, whose XAML is the following:
<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0"
Name="cbo_product" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Source=productsXml, XPath=@name}"
SelectionChanged="product_SelectionChanged"/>
The Products XML should be read-only--the user won't be able to change any values in the XML from the app. I just want to read the XML data and display it in the app.
I have a few questions:
- Am I going about this correctly? Having a standalone XML file from which my WPF app reads, having
[Serializable]
classes representing the nodes in the XML file for the purpose of extracting data from those nodes in C#, using an event handler to code dependencies between ComboBoxes, etc.
- Why don't my product names, e.g., MyProduct1, show up in my ComboBox? Currently it just shows up empty.
- It seems almost like having
[Serializable]
classes for representing my XML nodes is redundant/unnecessary since XAML already has the XmlDataProvider
/XPath stuff. Is this the case?
Edit:
Updated my ComboBox XAML to the following and now I see my list of Product names in the ComboBox, thanks to decyclone's answer:
<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0"
Name="cbo_product" VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Source={StaticResource productsXml}}"
DisplayMemberPath="@name"
SelectionChanged="product_SelectionChanged"/>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…