R – How to move the RoutedCommand handler from View-codebehind to ViewModel


The following RoutedCommand example works.

However, the handling for the button which executes the command is in the codebehind of the view. The way I understand MVVM, it should be in the ViewModel.

However, When I move the method to the ViewModel (and change it to public), I get the error "ManagedCustomersView does not contain a definition of OnSave". Even if I change the RoutedCommand second parameter to typeof(ManageCustomersViewModel), I get the same error.

How can I move the command handler from the View-codebehind to the ViewModel?


   <CommandBinding Command="local:Commands.SaveCustomer" Executed="OnSave"/>
<Button Style="{StaticResource formButton}" 
   CommandParameter="{Binding Id}"/>


private void OnSave(object sender
                    , System.Windows.Input.ExecutedRoutedEventArgs e)
    int customerId = ((int)e.Parameter);
        ("You clicked the save button for customer with id {0}.", customerId));


using System.Windows.Input;
using TestDynamicForm123.View;

namespace TestDynamicForm123
    public class Commands
        public static RoutedCommand SaveCustomer = 
             new RoutedCommand("SaveCustomer", typeof(ManageCustomersView));

Best Solution

You'll expose a property off your ViewModel that references the command.

class MyViewModel
    public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }

Then in the XAML

<Button Command="{Binding SaveCmd}" />

However you might find it easier to use the RelayCommand so that you can define the actual command logic in your model as well.

Related Question