Reputation: 24572
I have a ViewModel command that looks like this:
// Category Page
private ICommand openPageCmd;
public ICommand OpenPageCmd =>
openPageCmd ??
(openPageCmd = new Command<string>((pageType) => settingsPage.OpenPage(pageType)));
But instead of sending a string I would like to send an ID which is an int and a Name which is a string. Can someone tell me how I can do this?
Upvotes: 0
Views: 53
Reputation: 112602
You can create your own command by implementing ICommand
. Create a command having a constructor with the required parameters.
See:
public class MyCommand : ICommand
{
private int _id;
private string _name;
public MyCommand(int id, string name)
{
_id = id;
_name = name;
}
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
//TODO: Add your implementation
}
public event EventHandler CanExecuteChanged;
}
Or better, create your own relay command (generic reusable command):
public class RelayCommand<T> : ICommand
{
private readonly T _argument;
private readonly Action<T> _execute;
public RelayCommand(T argument, Action<T> execute)
{
_execute = execute;
_argument = argument;
}
public bool CanExecute(object parameter) => true;
public void Execute(object parameter)
{
_execute(_argument);
}
public event EventHandler CanExecuteChanged;
}
The view model
public class MyViewModel
{
private SettingsPage settingsPage = new ...;
public int Id { get; set; }
public string Name { get; set; }
public MyViewModel()
{
OpenPageCmd =
new RelayCommand<MyViewModel>(this, vm => settingsPage.OpenPage(vm.Id, vm.Name));
}
public ICommand OpenPageCmd { get; }
}
This allows the command to use the current values of the view model at any time.
Upvotes: 3