Search code examples
wpfmvvmconceptualrouted-commands

How to move my 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?

ManageCustomersView.xaml:

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

ManageCustomersView.xaml.cs:

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

Commands.cs:

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

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

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.