I've seen quite a few example of passing a parameter through a command using the RelayCommand class in MVVM Light, but there's one slight difference between what i want and what i have seen.
I want to create a few buttons where all have them have a ModuleType associated. And when their action is executed i want to know which ModuleType it is. And i wanted to do this in a code efficient way, so not having to create the RelayCommands manually, but instead do everything in a foreach loop, also because i don't know how many buttons i have to create at start.
So here is the code. In my 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;
}
}
I'm still learning about lambda expressions, so i guess i am doing something wrong on the initialization of the RelayCommand.