Vac*_*ano 2 c# generics wpf command
我正在使用此代码来创建一个简单的命令:
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
}
Run Code Online (Sandbox Code Playgroud)
我没写这个.但我喜欢使用它.当我使用它时,它最终会像这样:
// 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.
}
Run Code Online (Sandbox Code Playgroud)
唯一的问题是RunCommand的参数是一个对象.我想我被仿制药宠坏了.我总是希望IDE /编译器只知道我正在使用的类型是什么.
是否可以更改此SimpleCommand类以使用泛型实现?
当然.是否会指向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
}
Run Code Online (Sandbox Code Playgroud)
顺便提一下,你在问题中使用SimpleCommand有点迂回.而不是这个:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = x => RunCommand(x)
};
Run Code Online (Sandbox Code Playgroud)
你可能只有:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = this.RunCommand
};
Run Code Online (Sandbox Code Playgroud)
指定lambda实际上只有在你像这样进行内联工作时才有用:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = o => this.SelectedItem = o,
CanExecuteDelegate = o => o != null
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2656 次 |
| 最近记录: |