Published Monday, May 15, 2006 12:09 PM by martin

WPF, XmlDataProvider and Data Binding

I've never sat down to learn XPath properly, which means that whenever I need to write an XPath expression, it's a matter of trial-and-error.  Data binding to XML in WPF makes use of XPath, and although there are some useful tools around to help you formulate expressions, that wasn't going to stop me writing my own!

I came up with this.  It uses the Feb CTP WinFX bits, and I used the Mar CTP of Expression Interactive Designer to design it.  There are some points I want to draw your attention to...

1. I change the Source of the XmlDataProvider dynamically at runtime, to whatever filename you supply in the TextBox.  That you can do this seems quite powerful to me.

2. I change the XPath property of the ListBox's ItemsSource binding dynamically at runtime.  That you can do this seems, if anything, even more powerful to me.

3. I wanted my ListBoxItems to show the raw XML coming through the binding.  Normally you just want to see "data" coming out of your XML, so I wasn't sure how easy this would be.  Imagine my delight to find that each ListBoxItem is in fact bound to an XmlElement instance.  That means I can do this...

Text="{Binding Path=OuterXml}"

... and get the actual XML, whereas you would normally use an XPath expression in the binding.

4. The ListBoxItems generally contain enough text that they have to wrap to stay completely visible in the ListBox.  By default they were too wide, even though I set HorizontalAlignment="Stretch"; I just got a horizontal scrollbar on the ListBox, but I didn't want that.  I wanted the width to be constrained and the text to wrap so that only a vertical scrollbar would be needed.  I found that the ListBox contains a ScrollViewer, so I could do...

<ListBox ... ScrollViewer.HorizontalScrollbarVisibility="Disabled" ... />

... and hey presto! No horizontal scrollbar, and my items are sized perfectly to fit in the ListBox.

Now, to use the tool (if you need to play with XPath like I do)...  load an XML file using the TextBox at bottom-left, then just type some XPath into the TextBox at bottom-right.  As you type your XPath expression, the contents of the ListBox change dynamically to illustrate the results of the XPath you've entered.

Update: there's a new version of this sample that works with WinFX Beta 2.  Click here.