Ever wondered what the param in RelayCommad does? May sound silly though but can't find many samples explaining the same.
Before that, if you are not aware what a Relay Command in MVVM is, you may have to check out what MVVM foundation is all about. Relay Command is actually a commanding manager kinda stuff available with MVVM Foundation (search for the same in codeplex, you will come to know if you don't know) which could reduce the redundancy of the number of commands that may get created in a ViewModel's perspective.
A Relay Command implementation in general will look like
RelayCommand _openCommand
public ICommand OpenCommand
{
get
{
if (_openCommand == null)
{
_openCommand = new RelayCommand(param => this.Open,
param => this.CanOpen );
}
return _openCommand;
}
}
So what's the param doing there?
I initially thought it's just for the sake of the Lambda construct that we are having to write it. But then when i really came across instances where i had to pass a parameter to an Action or a Predicate, i knew param had something to say.
Let's say i have a situation where in need to pass a parameter to the Open Action as well as to the CanOpen Predicate.
RelayCommand _openCommand
public ICommand OpenCommand
{
get
{
if (_openCommand == null)
{
_openCommand = new RelayCommand(param => this.Open((string)param),
param => this.CanOpen((string)param) );
}
return _openCommand;
}
}
One of the ways of doing it would be to add a property (CommandParameter or something) in your ViewModel which you can bind with your controls CommandParameter.
public object CommandParameter { get; set; }
To make it more clear, let's think about an implementation where i need to open a file by passing the file path as the parameter. So the CanOpen predicate will function something like if i don't find the file to be opened in the defined path, i won't allow the OpenCommand to execute.
So in my code the implementation will look something like,
viewModel.CommandParameter = strFilePath;
Xaml Binding will have the Command and CommandParameter part related to whatever control we are binding to and the predicate will look something like.
public bool CanOpen(string strFilePath)
{
//if i can't find the file, i should not try to open it.
return File.Exists(strFilePath);
}
and similarly the Action part implementation
public void Open(string strFilePath)
{
//Open the file and i do whatever i want to do....
}
pretty neat in an environment where the path may be read dynamically from somewhere.
