2013-03-08 61 views
0

當我實現ICommand接口,下面的方法創建ICommand總是需要一個對象作爲參數嗎?

#region ICommand Members 

    public bool CanExecute(object parameter) 
    { 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
    } 

#endregion 

有趣的部分是

public void Execute(object parameter) 
{ 
} 

很簡單,因爲它表示,它預計1個參數。如果我不需要傳遞參數怎麼辦?在我的ViewModel我有以下代碼

public class DownloadViewModel : BaseViewModel 
{ 
    public ICommand BrowseForFile { get; set; } 

    public string File { get; set; } 

    public DownloadViewModel() 
    { 
     BrowseForFile = new RelayCommand(new Action<object>(OpenDialog)); 
    } 

    private void OpenDialog(object o) 
    { 
     var dialog = new System.Windows.Forms.FolderBrowserDialog(); 
     System.Windows.Forms.DialogResult result = dialog.ShowDialog(); 
     File = dialog.SelectedPath; 
    } 
} 

OpenDialog方法不需要參數,但如果我只是這樣我就可以滿足該接口出現。

我是否正確地做了這件事,還是錯過了這個觀點?

回答

2

是的,ICommand總是需要一個對象,RelayCommand也是。如果你不需要它,你傳遞null並且不要在你的方法中使用它,這很醜陋。

我會使用棱鏡的DelegateCommand來代替。這存在於非通用版本中,它不採用參數:

Command = new DelegateCommand(DoSomething); 
CommandWithParameter = new DelegateCommand<int>(DoSOmethingWithInt); 

它在PRISM組件中,您必須下載並參考。

using Microsoft.Practices.Prism; 

PRISM

或者,使用工具包MVVMLight,它提供了一個命令類,基本上做同樣的事情。無論如何,如果沒有MVVM框架,使用MVVM沒有意義。我可以推薦PRISM,它也是基本的東西,如DelegateCommandEventAggregator

+1

我認爲問題的關鍵是,OpenDialog是否需要一個參數 – Scroog1 2013-03-08 09:36:24

+1

我的理解是:「如果我不需要它,我如何擺脫命令操作中的參數?」 – Marc 2013-03-08 09:40:09

+0

有趣。這個問題似乎有些模棱兩可。我感覺OP是困惑的,並且認爲''OpenDialog''是執行''Execute''而不是僅僅由它調用。 – Scroog1 2013-03-08 09:47:49

2

Execute接受參數的事實與ViewModel中的方法無關。唯一影響OpenDialog需要的參數是您實施ICommand

如果實現,例如:

public class MyRandomCommand : ICommand 
{ 
    private readonly Action _action; 

    public MyRandomCommand(Action action) 
    { 
     _action = action; 
    } 

    public void Execute(object parameter) 
    { 
     _action(); 
    } 

    ... 
} 

然後沒有參數將需要您OpenDialog方法,你可以創建一個命令如下:然而

public ICommand Command { get { return new MyRandomCommand(OpenDialog); } } 

可以, ,需要您傳遞給您的命令的方法的任何簽名。

RelayCommand最常見的現成實現可以採用0或1參數的方法,並將適當地從Execute調用。

相關問題