2010-07-27 56 views
2

我使用這個代碼,以使一個簡單的命令:WPF SimpleCommand可能與泛型?

public class SimpleCommand : ICommand 
{ 
    public Predicate<object> CanExecuteDelegate { get; set; } 
    public Action<object> ExecuteDelegate { get; set; } 

    #region ICommand Members 

    public bool CanExecute(object parameter) 
    { 
     if (CanExecuteDelegate != null) 
      return CanExecuteDelegate(parameter); 
     return true;// if there is no can execute default to true 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 

    public void Execute(object parameter) 
    { 
     if (ExecuteDelegate != null) 
      ExecuteDelegate(parameter); 
    } 

    #endregion 
} 

我沒有寫這個。但我喜歡使用它。當我使用它時,它最終會變成這樣:

// This is the value that gets set to the command in the UI 
public SimpleCommand DoSomethingCommand { get; set; } 


public DoSomethingCommandConstructor() 
{ 
    DoSomethingCommand = new SimpleCommand 
         { 
          ExecuteDelegate = x => RunCommand(x) 
         }; 
} 

private void RunCommand(object o) 
{ 
    // Run the command. 
} 

唯一的問題是RunCommand的參數是一個對象。我想我被泛型所寵壞了。我總是希望IDE /編譯器能夠知道我正在使用的類型是不是在投射。

是否可以更改此SimpleCommand類以使用泛型實現?

回答

5

當然。是否會指向Prism的實現,但CodePlex源選項卡似乎不工作。它看起來像這樣:

public class SimpleCommand<T> : ICommand 
{ 
    public Predicate<T> CanExecuteDelegate { get; set; } 
    public Action<T> ExecuteDelegate { get; set; } 

    #region ICommand Members 

    public bool CanExecute(object parameter) 
    { 
     if (CanExecuteDelegate != null) 
      return CanExecuteDelegate((T)parameter); 
     return true;// if there is no can execute default to true 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add { CommandManager.RequerySuggested += value; } 
     remove { CommandManager.RequerySuggested -= value; } 
    } 

    public void Execute(object parameter) 
    { 
     if (ExecuteDelegate != null) 
      ExecuteDelegate((T)parameter); 
    } 

    #endregion 
} 

順便說一句,您在您的問題SimpleCommand的使用是有點迂迴。取而代之的是:

DoSomethingCommand = new SimpleCommand 
        { 
         ExecuteDelegate = x => RunCommand(x) 
        }; 

你可以只是:

DoSomethingCommand = new SimpleCommand 
        { 
         ExecuteDelegate = this.RunCommand 
        }; 

指定拉姆達真的只有有用的,如果你正在做的工作內聯這樣的:

DoSomethingCommand = new SimpleCommand 
        { 
         ExecuteDelegate = o => this.SelectedItem = o, 
         CanExecuteDelegate = o => o != null 
        }; 
+0

感謝答案和對棱鏡的觀點。我想這是你要顯示給我的鏈接:http://compositewpf.codeplex.com/SourceControl/changeset/view/48968#839830 – Vaccano 2010-07-27 20:18:22