I’m using an MDI solution (see http://wpfmdi.codeplex.com/) and MVVM.
I use one RelayCommand to bind the toolbar and/or menu to the Main ViewModel, like:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => CurrentChildViewModel.EditSelectedItem(),
param => ((CurrentChildViewModel != null) && (CurrentChildViewModel.CanExecuteEditSelectedItem))));
}
}
However, in the child window, to bind a button to the same functionality I need another RelayCommand which is almost equal except it calls the methods EditSelectedItem and CanExecuteEditSelectedItem directly. It would look like:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => EditSelectedItem(),
param => CanExecuteEditSelectedItem))));
}
}
I need about 10 and in the future maybe 50 or more of such commands so I like to do it the right way now.
Is there a way to prevent this or a better way to do this?
You can remove the first command from the main viewmodel, because the command in the child viewmodel is more than enough.
Just use the binding like this in the xaml markup:
Also if I understand your code correctly, it has the stipulation that if the
CurrentChildViewModelproperty is null than the command will be disabled.If you need such behavior, you should add this converter to your code and slightly rewrite the binding:
XAML: