WPF SimpleCommand可能有泛型? [英] WPF SimpleCommand possible with generics?
问题描述
我使用此代码来创建一个简单的命令:
I am using this code to make a Simple 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
}
没有写这个。但我喜欢使用它。当我使用它,它最终如下:
I did not write this. But I enjoy using it. When I use it it ends up being like this:
// 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 /编译器只知道我正在使用的类型是与投射。
The only problem with this is that the parameter of RunCommand is an object. I think I have been spoiled by generics. I always want the IDE/compiler to just know what the type I am working with is with out casting.
是否可以更改此SimpleCommand类使用泛型?
Is it possible to change this SimpleCommand class to be implemented using generics?
推荐答案
当然。将指向你的Prism的实现,但CodePlex源选项卡似乎不工作。它看起来像:
Sure. Was gonna point you to Prism's implementation, but CodePlex source tab seems to not be working. It would look something like:
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有点迂回。而不是这样:
Incidentally, your usage of SimpleCommand in your question is a little roundabout. Instead of this:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = x => RunCommand(x)
};
您可以只有:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = this.RunCommand
};
指定一个lambda真的只有在你这样做内联时才有用:
Specifying a lambda is really only useful if you're doing the work inline like this:
DoSomethingCommand = new SimpleCommand
{
ExecuteDelegate = o => this.SelectedItem = o,
CanExecuteDelegate = o => o != null
};
这篇关于WPF SimpleCommand可能有泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!