MVVM Command Routing Between Controls

1.3k Views Asked by At

I currently have a main View with a Button and a ContentPresenter which is bound to a property of the ViewModel which is another View (and associated ViewModel). Is there way to route a command from the a handler declared in the control loaded in the ContentPresenter? My reason for this is the main View contains the tool bar and the content presenter has the content. I am using the Microsoft MVVM template and the generated DelegateCommand class.

<Window ...>
   <Button x:Name="btnAction" Command="{Binding ActionCommand}" />
   <ContentPresenter Content="{Binding CurrentView}" />
</Window>
1

There are 1 best solutions below

2
On

You should create a command object which is a static object on a class that both the window and the control can see.

  public static class MyCommands
  {
     public static RoutedUICommend CoolCommand .....;
  }

Then you can bind the control's Command property to the command object, for example:

<Button Command="cmd:MyCommands.CoolCommand" />

Then you simply need to handle the command binding at the window level using the CommandBinding XAML element.

<CommandBinding Command="cmd:MyCommands.CoolCommand" Executed="My_Handler" />