Commands in WPF, Implementation question
I know I've already asked questions on this, but something that's just confusing. I'm doing a tutorial on WPF MVVM pattern, but it seems I cannot get it right, as in the tutorial, it doesn't go into detail on how to implement the ICommand interface. (not sure how correct it really is?!!)
I have the following implementation of ICommand:
class ViewCommand : ICommand
{
#region ICommand Members
private Predicate<object> _canExecute;
private Predicate<bool> _execute(object param);
public ViewCommand(Action<object> action)
{
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
开发者_如何学C public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
}
and now this use:
class StartViewModel : ViewModel
{
public ViewCommand startViewCommand;
public ViewCommand StartCommand
{
get
{
if (startViewCommand == null)
startViewCommand = new ViewCommand(
param => this.StartApplication()); // StartApplication returns void
return startViewCommand;
}
}
I cannot figure out what my constructor of the ViewCommand
class is supposed to do? In the StartViewModel
class it's using a lambda expression in the constructor, so there needs to be some delegate, but I'm not sure what and how it's meant to work with Execute and CanExecute. I put a Action<object>
, but it's probably wrong...
Lastly, can someone point me to a tutorial on how to implement ICommand that explains it?
Thanks!
Have a look at Josh Smith's tutorial pay attention to relay command, where he implements it.
Your _execute
delegate shouldn't be a Predicate<bool>
, it should be an Action<object>
. Anyway, why don't you use an existing class like Josh Smith's RelayCommand
, or MVVM toolkit DelegateCommand
?
精彩评论