I came across the following Q&A from the technical chat transcript from several months ago. Our WPF data binding expert Sam Bent was the one providing the great answers. It’s excellent information about the XmlDataProvider and I thought I’d share it here.
Q: What are the guidelines for using XmlDataProvider for Xml binding? Setting the data context directly on a control such as a list box seems to work.
A: That works fine for one-shot use. XDP is useful if:
1. you want to switch the source to a different XML file
2. you want to pre-filter the XML via an XPath query
3. it automatically reads the XML on a background thread – avoids blocking the UI
4. it gives a convenient place to share the data among several controls
5. it gives a convenient place to assign the XmlNamespaceManager (if your XML uses namespaces)
If you don’t need any of this, you can skip XDP.
Q: So two way binding utilizing the XmlDataProvider only works between the target and the “in memory” XML? Is there a way without doing my own XML file serialization to get WPF to write out the in memory XML back to the hard disk?
A: Correct. You have to do your own file serialization.
Q: I have a pretty straight forward XAML file which uses an XmlDataProvider and is binding that data to a ListBox (successfully). If I’ve specified two way binding mode, should the changes I make in any control tied to the XML get persisted back to the XML?
A: No. You’ll need to make the individual bindings two-way to get the values persisted into the (in-memory) XML.
Most bindings on editable properties are two-way by default (e.g. TextBox.Text, CheckBox.IsChecked, Slider.Value, etc.), so you don’t have to do anything special.
Q: I have observed a big performance problem data binding XML to a list view. If I change the document structure of a bound (to a listview) XmlDocument , I get to 100% cpu quickly. XmlDataProvider has a defer refresh property but this does not seem to work.
A: You’re right. There are two reasons for this:
1. Any change to the XML might affect any of the bindings (because XPath can depend on any node in the XML tree). So all the bindings need to re-query.
2. When the changes add/remove items for your ListView, the old ListView UI stays around for a while until it gets GC’d. Meanwhile it’s still listening to change notifications.
We’ve actually looked at this recently. Too late for V1, of course, but we have some ideas on how to improve this. I agree it’s painful. [Sam adds: Note that we did some work to improve the perf issues mentioned in the last exchange. It’ll be a lot better in WPF 3.5.]