ViewModel on top of XDocument

2019-05-10 07:22发布

问题:

I am working on a WPF application which has a treeview that represents an XML. I load the XML on to the XDocument, then bind the TreeView to this object.

Now using the MVVM pattern, I want to provide a ViewModel on top of XDocument. What are some of the things that I should implement in the ViewModel class.

I am thinking of,

  1. RoutedCommands that bind to ContextMenu commands on the TreeView to allow add node, remove node, modify node etc
  2. Logic to actually modify attributes and nodenames on the view.

Am I going in the right direction? What else should I do to make it cleaner, modular at the same time easy to understand.

Should I use RoutedCommands or implement ICommand interface and create my commands? How about using attached properties for CommandBindings? does it make sense to do it in the treeview app that I am talking about? I am a bit overwhelmed because of so many options available to implement this.

Does anyone have links, sample code that does this sort of thing? A reference implementation may be?

回答1:

I'm with you. I started with

(ui) <-> (xml)

where xml represented as LINQy XElements so I got PropertyChange notification.

I then added some stateless helper classes to help me deal with xml (expose properties, validate data, etc). I'd bundle up XElements in ObservableCollections so I could bind to them.

Read about M-V-VM, and decided to convert my helper classes into ViewModels. Problems: Helper classes live in the data model namespace which knows nothing about UI. Helper classes know how to convert database row into XElement, ViewModel should never see that. Helper classes deal with xml. ViewModel shouldn't know or care.

So I'm actually considering implementing

(ui) <-> (viewmodel) <-> (helper) <-> (xml)

but i just balk at raising PropChange events in helper only to reraise them in viewmodel.