如何将我的RoutedCommand处理程序从视图代码后台移动到ViewModel?

8
以下RoutedCommand示例有效。
但是,执行命令的按钮的处理程序在视图的codebehind中。我理解MVVM的方式应该在ViewModel中。
然而,当我将方法移动到ViewModel(并将其更改为public)时,我收到错误“ManagedCustomersView不包含OnSave的定义”。即使我将RoutedCommand的第二个参数更改为typeof(ManageCustomersViewModel),我也会收到相同的错误。
如何将命令处理程序从View-codebehind移动到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));
    }
}
1个回答

8
您需要在ViewModel中公开一个属性,该属性引用命令。
class MyViewModel
{
    public RoutedCommand SaveCmd{ get{ return Commands.SaveCustomer; } }
}  

然后在XAML中

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

然而,您可能会发现使用RelayCommand更容易,因为这样您可以在模型中定义实际的命令逻辑。


嗯,我添加了这两个代码片段,现在点击我的按钮没有任何反应。我可以删除UserControl.CommandBindings或者保留它,但是都没有效果。输出中也没有任何信息。我还需要改变什么? - Edward Tanguay
看一下RoutedCommand,它会让事情变得更容易。你可以在你的视图模型中使用return new RoutedCommand(p => MessageBox.Show("Saving."))来完成所有操作。 - Paul Alexander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接