WPF tuto’s – Forward commands

With the MVVM pattern, it’s quite difficult to handle context menu commands because context menu are not in the same tree view and we generally don’t want to bind on business commands that are in menu item view models. It’s the same problem for tool windows and so on, because we want to reuse the existing commands.

I describe below the “Forward” command pattern used in CBR. Note that MVVM is implemented via MVVMLight.

First, extend your ViewModelBase to have a ViewModelBaseExtended that will implement a ForwardCommand for all your view models. With also an overrideable method GetForwardCommandContext

CommandContext is an helper class that will contain the command to execute as string and an additional command parameter

#region ----------------COMMANDS----------------

private ICommand forwardCommand;
 public ICommand ForwardCommand
 {
 get
 {
    if (forwardCommand == null)
            forwardCommand = new RelayCommand<string>(
  delegate(string param)
  {
     Messenger.Default.Send<CommandContext>(GetForwardCommandContext(param),
           ViewModelBaseMessages.ContextCommand );
  },
  delegate(string param)
  {
    return CanForwardCommand(param);
  });
  return forwardCommand;
  }
 }

protected virtual CommandContext GetForwardCommandContext(string param)
 {
 return new CommandContext();
 }

protected virtual bool CanForwardCommand(string param)
 {
 return false;
 }

#endregion
 }

public class CommandContext
 {
 public string CommandName { get; set; }
 public object CommandParameter { get; set; }
 }

Continue reading “WPF tuto’s – Forward commands”

Advertisements