2

I am starting a new MVVM project with WPF, both of which I am unfamiliar with and wanted to make sure that I was using a proper MVVM approach.

I have the following:

  • I have a master user control that contains its own ViewModel and a TabControl
  • Each Tab contains a separate user control with their own ViewModels
  • When the MasterViewModel is created, one of its property gets set (let's call it MasterId)
  • I need to propagate that MasterId property change from the master view model to the child view models

I am wondering what is the simplest / best / proper MVVM approach for implementing this simple scenario?

Talisker
  • 177
  • 2
  • 16

1 Answers1

3

When it comes to TabControls and the like I tend to have the child view models within a collection of the MasterViewModel

 public ObservableCollection<ViewModelBase> Tabs { get; private set; }

When your ID gets set or your child view models get created then you can set properties on them

public int MasterId
{
    get { return _masterId; }
    set { _masterId = value;
          foreach(var vm in Tabs)
             vm.MasterId = value; 
          NotifyPropertyChanged("MasterId");  
        }
}
aqwert
  • 10,559
  • 2
  • 41
  • 61
  • This sounds like a great solution. One question though, which will show my inexperience with WPF, how do you map your ViewModelBase view models to your child user controls data contexts shown into the different tabs? Currently, my tabs are populated by my "child" user controls at **design-time**, so I cannot have the equivalent of the ObservableCollection in my MasterViewModel as you suggested in your answer. How should I change my design so it matches your proposal? Many thanks. – Talisker Apr 24 '12 at 20:20
  • Look at this answer that goes into using data templates. http://stackoverflow.com/a/5651542/373706. If you want to see the controls in designtime then you can use the `d:DataContext` method where you construct a designtime only viewmodel. – aqwert Apr 25 '12 at 20:30