我正在为WPF应用程序使用MVVM light。我有一个视图模型,其中包含几个使用RelayCommand的命令。由于每个命令的代码非常相似,因此我创建了一个GetCommand方法。但是,如果我在RelayCommand中使用参数,则生成的RelayCommand不起作用。如果我不使用参数,一切都可以正常工作(除了我不能传递一个值)。
谁能解释一下为什么会发生这种情况,还有什么其他的解决方案可以在不复制粘贴的情况下重用代码?
下面是我的代码的一个非常精简的版本,它只显示了重要的部分:
public class MainViewModel {
public RelayCommand commandOne = GetCommand("one");
public RelayCommand commandTwo = GetCommand("two");
public RelayCommand GetCommand(string param) {
return new RelayCommand(() => {
// Do something accessing other properties of MainViewModel
// to detect if another action is alreay running
// this code would need to be copy & pasted everywhere
if(param == "one")
_dataService.OneMethod();
else if(param == "two")
_dataService.TwoMethod();
else
_dataService.OtherMethod();
var name = param;
});
}
}发布于 2013-11-27 22:33:19
这就是我通常使用RelayCommands的方式,我只是将命令绑定到方法。
public class MainViewModel {
public MainViewModel()
{
CommandOne = new RelayCommand<string>(executeCommandOne);
CommandTwo = new RelayCommand(executeCommandTwo);
}
public RelayCommand<string> CommandOne { get; set; }
public RelayCommand CommandTwo { get; set; }
private void executeCommandOne(string param)
{
//Reusable code with param
}
private void executeCommandTwo()
{
//Reusable code without param
}
}发布于 2013-11-28 01:29:13
您可能正在寻找类似以下内容的内容
public partial class MainWindow : Window
{
private RelayCommand myRelayCommand ;
private string param = "one";
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
public RelayCommand MyRelayCommand
{
get
{
if (myRelayCommand == null)
{
myRelayCommand = new RelayCommand((p) => { ServiceSelector(p); });
}
return myRelayCommand;
}
}
private void DoSomething()
{
MessageBox.Show("Did Something");
}
private void ServiceSelector(object p)
{
DoSomething();
if (param == "one")
MessageBox.Show("one");
else if (param == "two")
MessageBox.Show("two");
else
MessageBox.Show("else");
var name = param;
}
}https://stackoverflow.com/questions/20244455
复制相似问题