Adding Controls to an Application with WPF - Databinding
(Page 3 of 4 )
Next, the XML file needs to be wired into the ListBox. The first step is to make the data in the XML file accessible to the application by creating an XmlDataProvider. This can be done in the application's XAML, so no code is required. The XmlDataProvider is an example of a resource, which we can define once and use in multiple places. Resource definitions go in the appropriate Resources section. The XML file only needs to be used inside of Window1, and so we need to first create an object.Resources element as a child of Window1's Window element:
<Window.Resources>
</Window.Resources>
Then, the XmlDataProvider needs to be created within this section:
<XmlDataProvider x:Key="tasks" Source="Tasks.xml" XPath="Tasks/Task" />
There are three attributes that we define. The first is x:Key, which provides the resource with a unique identifier. The second is Source, which, of course, points to the source XML file. The third is XPath, which is set to the query used to generate the collection of elements. Here, we need access to the Task elements, which are located inside of the Tasks root element.
The next step is to hook the ListBox up to the XmlDataProvider. This is really simple to do. Replace the existing ListBox declaration with this:
<ListBox Name="TaskListBox" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Source={StaticResource tasks}}" />
Above, we specify the ItemsSource attribute. We connect it to the XmlDataProvider using its x:Key, tasks.
Next: Working with templates >>
More Windows Scripting Articles
More By Peyton McCullough