代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何将我的RoutedCommand处理程序从视图代码隐藏移到视图模型?

  •  8
  • Edward Tanguay  · 技术社区  · 16 年前

    下面的routedcommand示例工作正常。

    但是,对执行命令的按钮的处理 在视图后面的代码中 . 我理解MVVM的方式,它 应该在ViewModel中 .

    但是,当我将方法移动到ViewModel(并将其更改为public)时,我会得到错误“ ManagedCustomersView不包含OnSave的定义 “。即使我将routedcommand的第二个参数更改为typeof(manageCustomersViewModel),也会得到相同的错误。

    如何将命令处理程序从视图代码移到视图模型?

    经理客户视图.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}"/>
    

    经理客户视图.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 回复  |  直到 12 年前
        1
  •  8
  •   Paul Alexander    16 年前

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

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

    然后在XAML中

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

    不过,您可能会发现使用 RelayCommand 这样您就可以在模型中定义实际的命令逻辑。