为什么ViewModel不在MVVM中实现ICommand

时间:2013-03-13 17:53:27

标签: mvvm delegates viewmodel icommand

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

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

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

ViewModel:

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
    }
}

DelegateCommand:

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;
    }
.
.
.
}

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:3)

简短回答:因为您的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; }
}

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

答案 2 :(得分:0)

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