I am trying to call the same command from two different presentation models, but I got stuck during their design (both for command models and for viewing).
First I created the ViewModel1 view model class:
public class ViewModel1 : DependencyObject { ...
And the class of the ProcessMyString command:
public class ProcessMyString : ICommand { private ViewModel1 viewModel; public ProcessMyString(ViewModel1 viewModel) { this.viewModel = viewModel; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { viewModel.ProcessMyString(); } }
Then I created the second class of the ViewModel2 view model, but when I realized that this view model would also need to use the same command , the command constructor
public ProcessMyString(ViewModel1 viewModel)
will not work because it accepts the ViewModel1 parameter, and I need to be able to pass both view models. Then I decided to create a ViewModelBase class and make both view models from it. Of course, I also modified the command constructor:
// Constructor parameter is now ViewModelBase public ProcessMyString(ViewModelBase viewModel)
But this meant that the Execute(object parameter) command method is now called the method from ViewModelBase . This is a good application, because ViewModel calls ProcessMyString() , should only be reserved for the ViewModel1 and ViewModel2 classes. If I had a ViewModel3 class, I would not want it to call ProcessMyString() , and if I do not extend it from ViewModelBase , that would be fine.
But what happens if I need a command that is split between ViewModel2 and ViewModel3 ?
The question of summation: how do I organize my teams and view models so that presentation motives can use the same commands?