![](/img/trans.png)
[英]MVVM Light: About extracting the RelayCommand navigation parameter
[英]Dynamically assigning a parameter to a RelayCommand in MVVM Light
我已经看到了很多使用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的初始化上做错了。
如果执行foreach
循环并在lambda表达式中使用loop变量,则将其捕获。 不幸的是,变量的作用域不正确(至少在C#的较早版本中,此变化随C#5的变化而变化 (感谢Mafii))。
因此,您需要执行以下操作:
foreach (ModuleType mod in modules)
{
// New variable that is locally scoped.
var type = mod;
_navBarButtons.Add(new NavButton(mod.ToString(),
new RelayCommand<ModuleType>(param => ButtonExecute(type)), type));
}
关于HB发布的解决方案:不知道为什么它不能与lambda函数一起使用,为什么在按下按钮时不执行ButtonExecute。 而且我也不理解在foo为空并传递给该函数时定义lambda函数(如“ foo => ButtonExecute(foo)”)的逻辑。 但无论如何...
这是我所做的并且正在工作:
模型
<ItemsControl Name="NavButtonsItemsControl" ItemsSource="{Binding NavBarButtons}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding ButtonContent}" CommandParameter="{Binding ButtonModuleType}" Command="{Binding ButtonCommand}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ViewModel (检查我的初始问题中的其余代码)
.........
_navBarButtons.Add(new NavButton(mod.ToString(), new RelayCommand<ModuleType>(ButtonExecute), type));
.........
private void ButtonExecute(ModuleType state)
{
WriteToLog("Command with parameter " + state.ToString());
}
您可以使用Object而不是ModuleType使其更通用。 解决方案不是使用lambda函数,而是在按钮中定义CommandParameter绑定,并将该值作为execute函数中的参数。 我认为绑定没有明确定义,这就是为什么我很难理解该值如何达到“ ButtonExecute”的原因,但是按照Dominik Schmidt教程中的步骤进行工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.