views:

728

answers:

1

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));
    }
}
+2  A: 

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.

Paul Alexander
hmm, I added those two bits of code and now clicking my button does nothing. I can take out the UserControl.CommandBindings or leave it but that has no effect. Nothing in Output. What else do I need to change?
Edward Tanguay
Take a look at the RoutedCommand which makes it a lot easier. You can do return new RoutedCommand( p => MessageBox.Show( "Saving." ) ) all from within your view model.
Paul Alexander
I think the previous commenter meant RelayCommand.
Robert Taylor