Sunday 3 March 2013

Part 3: Binding ListBox to XML

This post is the third in the series of ListBox control. Here is the reference of all the post in this series for quick reference.

Part - 1: ListBox basics - Adding Items manually to ListBox and understanding properties of ListBox

Part - 2: Data Binding in ListBox (Binding ListBox to data source)

Part - 3: Binding ListBox to XML

Part - 4: Applying style to ListBox

Part - 5: Applying style to ListBox, Continued

Part - 6: ListBox custom ControlTemplate

 

Part 3: Binding ListBox to XML

WPF provides very handy control “XmlDataProvider” that can be used to load XML from variety of sources (i.e provides xml data in XAML, separate XML file or set the XMLDocument programmatically).

In XAML below, we added XmlDataProvider to windows resources and provided xml data in XAML.

<XmlDataProvider x:Key="FruitsXML">
<x:XData>
<Fruits>
<Fruit Name="Apple">
<ImagePath>Images\\Apple.png</ImagePath>
<Calories>61</Calories>
<Vitamins>A,C</Vitamins>
</Fruit>
<Fruit Name="Orange">
<ImagePath>Images\\Orange.png</ImagePath>
<Calories>51</Calories>
<Vitamins>A,B1,C</Vitamins>
</Fruit>
</Fruits>
</x:XData>
</XmlDataProvider>


Binding ListBox to XmlDataProvider

<ListBox Name="lstFruits" ItemsSource="{Binding Source={StaticResource ResourceKey=FruitsXML}, XPath=Fruits/Fruit}" DisplayMemberPath="@Name" SelectedValuePath="ImagePath"></ListBox>


There are 4 important parts in binding:



Binding Source is FruitsXML which is a XmlDataProvider static resource defined in windows resources section.


XPath: Source is set to entire xml data. Hence we set XPath to “Fruits/Fruit” which binds ListBox to all Fruit elements.


DisplayMemberPath: Each item in ListBox is bound an instance of Fruit element from XML, so we need to choose which child element/attribute of Fruit element to display. We choose to display Name attribute. “@” symbol is used to indicate attribute.


SelectedValuePath: SelectedValuePath is set to “ImagePath” element of Fruit. Hence when we access “SelectedValue” property in code, it will return ImagePath of selected item.


Using XML File instead of static XML data


XmlDataProvider has Source property which can be used to specify path of XML file to load data. We can move XML data provided in XAML to separate XML file and then specify Source property of XmlDataProvider XML file. Remaining code would be same for binding ListBox.

No comments:

Post a Comment