以下RoutedCommand示例有效。

但是,执行命令的按钮的处理是在视图的代码隐藏中。我理解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));
    }
}
有帮助吗?

解决方案

您将从ViewModel中公开一个引用该命令的属性。

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

然后在XAML中

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

但是,您可能会发现使用 RelayCommand 更容易您也可以在模型中定义实际的命令逻辑。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top