Hello,
having used WPF for quite a while, my applications are growing bigger. I would like to start using the MVVM pattern, but I have great difficulties getting an good understanding of some basic things. Each time I try to implement tutorials I run into trouble really fast, cause it seems I want things that reach beyond the level of most tutorials (ie. I want more than add simple records to a single ICollection...).
Specifically, for example:
- The idea is to omit code-behind, so I declare an instance of a class called ViewModelMainWindow in MainWindow.xaml, and set the DataContext of the MainWindow view to that instance. Now I can easily bind to members of that ViewModel class in my View. But suppose I load some file in the ViewModel, ie. I load an instance of my Model, and want to display portions of it in different Views. How do I set the DataContext for these views during runtime? My ViewModel does not know Names of elements in View, so I cannot set it in code. Now how will the different views know which data to bind to?
- Another problem I face time and again: suppose the Model has a List<Element1>, each Element1 has a List<Element2>, each Element2 has a List<Element3>. I can create a ViewModel for Element1, but it seems like a lot of work to build a similar cascaded structure of ViewModels, and then build complicated code keep the Model data up to date as well (ie. when items are added to collections, which I wanna do in 1 view at different levels, eg. in a treeview via Context Menu items). What is to keep me from building the Model using ObservableCollection<> for each level (which I can also easily serialize and deserialize (eg. to XML)) and easily databind directly to the view, in code-behind? That seems so much easier in these cases
At the same time, I do see that on the longer run, an approach of directly binding View and Model will ruin my code... So far, however I seem to be unable to get to terms with the issues described, and keep running around in circles...
Thanks for any pointers. Maybe my apporach of the matter also needs adjustment... I really wish there was a good book on the subject, which would dig deeper than the most tutorials.
Thank you, Menno