【发布时间】:2016-11-11 01:22:17
【问题描述】:
我已经看到了很多使用 MVVM Light 中的 RelayCommand 类通过命令传递参数的示例,但是我想要的和我看到的之间存在细微差别。
我想创建一些按钮,它们都具有关联的 ModuleType。当他们的动作被执行时,我想知道它是哪个 ModuleType。我想以一种代码高效的方式来做这件事,所以不必手动创建 RelayCommands,而是在 foreach 循环中做所有事情,也是因为我不知道在开始时我必须创建多少个按钮。
所以这里是代码。在我的 ViewModel
public ModuleSelectionViewModel(MachineStatusModel model, int order, List<ModuleType> modules) : base(model)
{
........
// create button for each of the modules
foreach (ModuleType mod in modules)
{
_navBarButtons.Add(new NavButton(mod.ToString(), new RelayCommand<ModuleType>(exec => ButtonExecute(mod)), mod));
}
RaisePropertyChanged("NavBarButtons");
}
// Binding to the Model
public ObservableCollection<NavButton> NavBarButtons
{
get { return _navBarButtons; }
}
// Execut Action
public void ButtonExecute(ModuleType mod)
{
WriteToLog("Selected " + mod.ToString());
}
// Support class
public class NavButton
{
public string ButtonContent { get; set; }
public ICommand ButtonCommand { get; set; }
public ModuleType ButtonModuleType;
public NavButton(string content, ICommand relay, ModuleType moduleType)
{
this.ButtonContent = content;
this.ButtonCommand = relay;
this.ButtonModuleType = moduleType;
}
}
我还在学习 lambda 表达式,所以我想我在 RelayCommand 的初始化上做错了。
【问题讨论】:
-
到底是什么问题?
-
@DevNewb:总而言之,我想按下一个按钮并使用参数触发执行功能。每个按钮对该参数都有不同的值
-
从您的问题中不清楚您提供的代码中究竟有什么不起作用
-
@DevNewb 看看关于答案 H.B. 的讨论。给了。此时这部分不起作用'param => ButtonExecute(type))',ButtonExecute 不会执行。我希望它使用创建时传递的参数执行该函数'... new RelayCommand
(param => ButtonExecute(type)) ...'
标签: c# wpf mvvm mvvm-light relaycommand