During the session that I gave last Saturday a lot of people where suprised that there was more to WPF than just fancy graphics. While explaining the power of databinding I noticed people getting enthusiastic about the possibilities. So I will be posting a couple of Blog posts about Databinding in WPF.
Part 1 : Exposing my data to my application
In WPF there are numerous ways of exposing data to your application. In the example I will be giving I will focus on XML because it’s made so incredibly easy in WPF and Visual Studio 2008. WPF introduces the XmlDataProvider, a class which can be attached to any XML file. (or in this case, a RSS file). XmlDataProvider can be declared in XAML
Notice the level where I declare the XmlDataProvider. I chose the Window because I know my data will be used by a couple of different sources inside this window. XmlDataProvider supports the XPath attribute where I can use any XPath query I want to direct to the data I want to show. In this case, all news items in the channel.
For now, don’t mind the IsAsynchronous and IsInitialLoadEnabled, they are simply there to make the data load on startup but not hold up the visual thread whenever the data can’t be reached.
I have to declare a NameSpaceMapping for the ‘media:’ extension in my RSS file. Just like you have to do when using the x: prefix in your XAML file. I do this by declaring a NameSpaceMappingCollection in the XmlNameSpaceManager property of the XmlDataProvider.
In order to control the visual output of my data I create a CollectionViewSource in which I can Filter, Sort and Group. I can do this by simply referring to the XmlDataProvider in the Source property.
Finally, in order to expose this data to elements in my window I have to add a reference to this CollectionView to the DataContext property of one of the desired elements. We’ll choose for the overlaying Grid element. This means that every element within this grid can access and manipulate the expose data.
Summary
Now I have the data available through a CollectionView attached to the DataContext of our main grid. Next up is binding this collection to a target. In my example, a Listbox a Hyperlink and a TextBlock.


0 Responses to “DataBinding in WPF (Part 1)”