WPF XML Databinding for Noobies


I must admit the new databinding in WPF is very nice and very simple -apparently just not simple enough as i struggled with the xpath syntax and thought i would share my findings. 


 


Starting with an XML file called XMLFile1.xml with the following contents:



<?xml version=”1.0″ encoding=”utf-8″ ?>
<Questions>
   <Question
   QID=”1″
   QText = “How many KG of Carbon does a stove take to…?”
   Correct_answer = “15kg
   Wrong_answer1 =”12kg
   Wrong_answer2 =”16Kg
   Notes =”It is a little known fact Carbon is black…”
   Resource=”Carbon
   Fixturetype=”Stove
   Image=”image.jpg“>
</Question>


</Questions>


 


There are a couple of ways to reference the Question Values like Qtext. 


Starting with the XmlDataProvider give it a name (x:Key) and set the source to the XML Document(see below):



<XmlDataProvider x:Key=”dataProvider” XPath=”Questions” Source=”XMLFile1.xml”/>


Note i set the Xpath in the Provider but depending on the how you reference the XPath in your binding this may not be needed such as the example below.



<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=//Question/@QText }” />


Typically you would set the Xpath in the Provider such as in this example, it would be required:



<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=Question/@Correct_answer }” />


The complete application running would look like the following: (This assumes the XMLFile1.XML is in the same directory as the application)


 


<Window x:Class=”WPFDataBinding.Window2″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
>
<Window.Resources>
<XmlDataProvider x:Key=”dataProvider” XPath=”Questions” Source=”XMLFile1.xml”/>
</Window.Resources>
<StackPanel Margin=“10”>
<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=//Question/@QText }” />
<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=Question/@Correct_answer }” />


<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=Question/@Correct_answer1}” />


<TextBox Text=”{Binding Source={StaticResource dataProvider}, XPath=Question/@Correct_answer2}” />
</StackPanel>
</Window>


 


Big Thanks to Deepak for pointing out what i was doing wrong with my Xpath references!