为什么ViewModel没有';t在MVVM中实现ICommand

为什么ViewModel没有';t在MVVM中实现ICommand,mvvm,delegates,viewmodel,icommand,Mvvm,Delegates,Viewmodel,Icommand,我试图了解WPF应用程序的MVVM 在下面的示例中,我们使用从ICommand继承的委托,然后在ViewModel中实例化该委托并提供适当的实现 我的问题是为什么我们不能让ViewModel实现ICommand 视图模型: public class ViewModel : INotifyPropertyChanged { public ViewModel() { InitializeViewModel(); } protected void In

我试图了解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
    }
}
公共类视图模型:INotifyPropertyChanged
{
公共视图模型()
{
初始化eviewModel();
}
受保护的void InitializeViewModel()
{
DelegateCommand MyCommand=新建DelegateCommand(
SomeCommand\u Execute,SomeCommand\u CanExecute);
}
void SomeCommand\u Execute(SomeClass arg)
{
//实施
}
bool SomeCommand_CanExecute(SomeClass arg)
{
//实施
}
}
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;
    }
.
.
.
}
公共类DelegateCommand:ICommand
{
公共DelegateCommand(Action execute):这个(execute,null){}
公共DelegateCommand(Action execute,谓词canExecute):this(execute,canExecute,“””{}
公共DelegateCommand(操作执行、谓词canExecute、字符串标签)
{
_执行=执行;
_CanExecute=CanExecute;
}
.
.
.
}

您可以通过这种方式实现
ICommand
——这是实现
ICommand
的一种非常常见的方式。尽管如此,您仍然需要在ViewModel上设置
MyCommand
属性才能绑定到它。

原因是视图和命令数量之间存在一对多关系

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


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

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

此外,ViewModel可以包含多个命令

公共类视图模型:INotifyPropertyChanged
{
公共视图模型()
{
初始化eviewModel();
OpenCommand=新的DelegateCommand(
param=>{…},
param=>{return true;});
SaveCommand=新的DelegateCommand(
param=>{…},
param=>{return true;});
SaveAsCommand=新的DelegateCommand(
param=>{…},
param=>{return true;});
}
公共ICommand OpenCommand{get;private set;}
公共ICommand SaveCommand{get;private set;}
public ICommand SaveAsCommand{get;private set;}
}
现在可以将这些命令绑定到视图,因为它们是一个属性