I have encountered a problem while using the MVVM model in WPF. Here are my objects:
Views
-
MainWindow(View)
(DataContext for this view binds to MainWindowViewModel) -
ItemViewWindow
(DataContext for this binds an ItemListViewModel)
View-Models
-
MainWindowViewModel
(contains:
ObservableCollection Items) -
ItemListViewModel
(contains:
ObservableCollection Items,
ItemViewModel SelectedItem,
Other properties/commands)
ItemViewWindow is accessed by a menu button on the MainWindow. I want to be able to pass just the collection from the MainWindow to the ItemView (note: I can’t set it as the DataContext because it needs an ItemListViewModel). Then any changes made there should be reflected back in the MainWindow.
I know one way is to have the ItemListViewModel as a property of MainWindowViewModel instead of the Collection, then I can just pass that as the DataContext, but it seems wrong to have the extra functionality of the ItemListViewModel in the MainWindowViewModel. Is there a more elegant way of doing this without using the UI code-behind?
Why not either:
a: Make ItemListViewModel expose a property on which you assign the collection e.g.
Then just set it when you instantiate the ItemVM in the MainWindowViewModel
Or…
b: Use something like the
EventAggregatorpattern to publish a message containing the collection for the ItemListViewModel to subscribe toThe first method seems more straightforward