【问题标题】:Why the ViewModel doesn't implement ICommand in MVVM为什么 ViewModel 没有在 MVVM 中实现 ICommand
【发布时间】:2013-03-13 17:53:27
【问题描述】:

我正在尝试了解用于 WPF 应用程序的 MVVM

在下面的示例中,我们使用一个继承自 ICommand 的委托,然后在我们的 ViewModel 中,我们实例化该委托并提供适当的实现

我的问题是为什么我们不能让 ViewModel 实现 ICommand?

视图模型:

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        InitializeViewModel();
    }

    protected void InitializeViewModel()
    {
        DelegateCommand MyCommand = new DelegateCommand<SomeClass>(
            SomeCommand_Execute, SomeCommand_CanExecute);    
    }

    void SomeCommand_Execute(SomeClass arg)
    {
        // Implementation
    }

    bool SomeCommand_CanExecute(SomeClass arg)
    {
        // Implementation
    }
}

委托命令:

public class DelegateCommand<T> : ICommand
{
    public DelegateCommand(Action<T> execute) : this(execute, null) { }

    public DelegateCommand(Action<T> execute, Predicate<T> canExecute) : this(execute, canExecute, "") { }

    public DelegateCommand(Action<T> execute, Predicate<T> canExecute, string label)
    {
        _Execute = execute;
        _CanExecute = canExecute;
    }
.
.
.
}

【问题讨论】:

    标签: mvvm delegates viewmodel icommand


    【解决方案1】:

    原因可能是您的视图和命令数量之间存在一对多关系。

    通常每个视图都有一个视图模型。但是您可能希望单个视图有许多命令。如果要将 ViewModel 用作命令,则必须有多个 ViewModel 实例。

    典型的实现是您的 ViewModel 将包含您的 View 需要的所有命令的实例。

    【讨论】:

      【解决方案2】:

      简短回答:因为您的 ViewModel 不是命令。

      此外,您的 ViewModel 可以保存多个命令。

      public class ViewModel : INotifyPropertyChanged
      {
          public ViewModel()
          {
              InitializeViewModel();
      
              OpenCommand = new DelegateCommand<SomeClass>(
                  param => { ... },
                  param => { return true; }); 
      
              SaveCommand = new DelegateCommand<SomeClass>(
                  param => { ... },
                  param => { return true; });
      
              SaveAsCommand = new DelegateCommand<SomeClass>(
                  param => { ... },
                  param => { return true; });
          }
      
          public ICommand OpenCommand { get; private set; }
      
          public ICommand SaveCommand { get; private set; }
      
          public ICommand SaveAsCommand { get; private set; }
      }
      

      现在您可以将这些命令绑定到您的视图,因为它们是一个属性。

      【讨论】:

        【解决方案3】:

        您可以通过这种方式实现ICommand - 这是实现ICommand 的一种非常常见的方式。话虽如此,您仍然需要在 ViewModel 上创建 MyCommand 属性才能绑定到它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-30
          • 1970-01-01
          • 1970-01-01
          • 2012-07-12
          • 2013-10-28
          • 1970-01-01
          • 2010-10-03
          • 1970-01-01
          相关资源
          最近更新 更多