Complex data structure in ViewModel layer of the MVVM
I have large collection of MyFile objects which are linked in all kind of ways between each other like spaghetti. In addition, from this collection I create smaller subcollections of some items that are equal by some criteria. (for example all files with the extension .txt, all files that belong to certain directory etc...)
Basically I have complex structure of linked lists in my business logic. Now I want to create ViewModel for this in order to prepare it for View and this is where I hit the wall. I just can't figure out how to prepare this mess and still keep everything efficient and organized.
First problem is that wrapping each collection in collectionViewModel by enumerating item by item and creating itemViewModel will create duplicate itemViewModel for each item (since one item can be contained in several collections)
Second problem is how to keep everything updated? If for example an item1 in business logic changes its reference from item2 to item3, then ViewModels should update them accordingly.
I am really tem开发者_开发技巧pted to break from the MVVM pattern here even though I dont want it, and put bussines + presentation logic in one object/class since this spaghetti structure seems a bit too much for my level of understanding of MVVM.
Thanks
Maybe I'm barking up the wrong tree here, but here goes.
You could have a Model which acts as a repository for all your file objects, and that also exposes an ItemAdded and ItemRemoved event, plus a Query method. You can then have a common ViewModel type that represents your view on this model (a ViewModel), but specializes by composing a query. In this way you can have ViewModel+Query (e.g. all files with extension txt) instance for each view you need to represent. The ViewModel would be responsible for executing the query on your Model (by calling the query method) and then turning the results into an observable collection of file items (or what-have-you). You can update your ViewModel in response to Model changes by subscribing to ItemAdded and ItemRemoved events. If on an ItemRemoved event your ViewModel file items collection contains the item, then remove it. If on an ItemAdded event the item matches the query condition for that ViewModel instance, then add it to the collection.
This allows you to have a single Model for all your files, and then a ViewModel(+Query) instance for each type of view you wish to represent. The ItemAdded and ItemRemoved event allow you to update your ViewModel. As the items in the ViewModels are observable collections, your databound views will update themselves.
精彩评论