WPF advice on XML data binding: XmlDataPresenter vs custom class?
I'm just starting out in WPF and I'm building a simple movie library as a test project to help me find my feet.
I'm storing my movie information in XML, for example:
<movie id="1" title="Back To The Future" date="1985" ... />
The movies appear in a list and when clicked the fields will become editable. I've got that working by using two Data Templates to style the list items, applied via a Trigger on the ListBoxItem.IsSelected property.
But for binding and editing the data, I'd be really grateful for some advice. I've tried each of the approaches below with varying degrees of success. Which do you think makes the most sense? Are there any other things I could try?
Approach 1: Bind to XML directly using XMLDataProvider in XAML. In this case the ListBox binds to the XmlDataProvider and the individual control elements are bound via XPath expressions. It's very simple to get started, but this approach seems to become tricky when editing the data. We need rather a lot of ValueConverters just to ensure that the data is presented sensibly and saved back to the XML file in the appropriate format.
Approach 2: Create a custom Movie class that receives the XML and exposes all the movie attributes as public properties to which the controls are bound. This feels more robust and flexible, but seems to require a lot more work to implement. Every property needs to 开发者_Python百科be explicitly exposed in code and validation is a pain.
Approach 3: A bit like approach 2 but with a Movie user control instead of the ListBox + Data Templates. I started with this and quickly abandoned it because I couldn't see any advantages over approach 2.
I realise it's not a straightforward question and that there are a lot of factors to consider, but any thoughts on the various pros/cons (or whether there are any tricks I'm missing) would be appreciated. Please let me know if you would like more info or code samples. And apologies if this question is inappropriate or unwelcome.
Many thanks.
If its just for displaying, whether or not you use templates, approach one is more efficient as the wpf engine works directly with the xml.
If your going to do editing operations on the data, it is best to go with Approach two as you have the flexibility to manipulate the data far better. Using a class you can do the exact same thing as in approach one with binding as the engine will read from the objects just like the xml file. This approach allows for easily binding the elements 2 way and if its from an IObservable Collection, you can ovveride the method that is called when the data is changed, so it updates the xml.
精彩评论