Search code examples
wpfmvvmlistboxviewmodeldatacontext

MVVM - Menu View with Preview View (Shared ViewModel) approach


I've just started my journey with MVVM and WPF and I need an advice to solve my problem or rather guide me towards right solution.

Link to image: https://s12.postimg.org/md0h6fv3x/Simple_App.png enter image description here

Description (what I want to achieve):

  • View A is a menu (UserControl) with ListBox and DataContext: V.ObservableCollection

  • View B is a preview to selected item from View A ListBox

  • View A & B are loaded from MainWindow

What is simpliest and cleanest approach to achieve that?

  1. I was thinking about sharing the same ViewModel with View A&B. Create a SelectedItem property in ViewModel and then put it MainWindow's resources and bind datacontext to View A & B

    • Is it valid approach? Will that VM be updated properly in both views if it get changed?
  2. Somehow bind View's A listbox SelectedItem to View B preview mode but don't know how.


Solution

    1. Use only one ViewModel. Eg; Pseudo code :

      public class ViewModel : INotifyPropertyChanged
      {
        public ObservableCollection<Employee>{get;}          
      
        /* provide change notification in ChosenItem */
        public Employee ChosenItem{get;set;}
      }
      
    2. Use this ViewModel as DataContext for both Views.