2013-03-13 98 views
2

我想了解MVVM爲WPF應用程序爲什麼視圖模型不MVVM

在下面的例子中,我們使用的是從ICommand的繼承,那麼在我們的視圖模型的委託實現ICommand的,我們實例委託並提供相應的實現

我的問題是爲什麼我們不能讓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 
    } 
} 

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

原因是您的視圖和您的命令數量之間存在一對多的關係。

對於每個視圖,通常都會有一個ViewModel。但是您可能希望爲單個視圖提供許多命令。如果您要將您的ViewModel用作命令,則必須擁有ViewModel的多個實例。

典型的實現方式是,您的ViewModel將包含您的View所需的所有命令的實例。

0

您可以實現ICommand這樣 - 這是實現ICommand一種很常見的方式。也就是說,你仍然需要在ViewModel上創建一個屬性MyCommand以綁定它。

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

現在,您可以將這些命令綁定到您的視圖,因爲它們是屬性。