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類以使用泛型實現?
感謝答案和對棱鏡的觀點。我想這是你要顯示給我的鏈接:http://compositewpf.codeplex.com/SourceControl/changeset/view/48968#839830 – Vaccano 2010-07-27 20:18:22