How to move my RoutedCommand handler from View-codebehind to ViewModel?
Asked Answered
A

1

8

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));
    }
}
Awhirl answered 30/4, 2009 at 7:53 Comment(0)
M
8

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.

Marcin answered 30/4, 2009 at 7:56 Comment(2)
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?Awhirl
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.Marcin

© 2022 - 2024 — McMap. All rights reserved.