Passing a command parameter to a Silverlight command using MVVM

I am just learning Silverlight and looking at MVVM and Commanding.

So, I saw the basic implementation of RelayCommand:

public class RelayCommand : ICommand { private readonly Action _handler; private bool _isEnabled; public RelayCommand(Action handler) { _handler = handler; } public bool IsEnabled { get { return _isEnabled; } set { if (value != _isEnabled) { _isEnabled = value; if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } } public bool CanExecute(object parameter) { return IsEnabled; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _handler(); } } 

How to pass parameter with command using this command?

I saw that you can pass CommandParameter as follows:

 <Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... /> 

In my ViewModel, I need to create a command, but RelayCommand expects an Action delegate. Can I implement RelayCommand<T> with Action<T> - if so, how to do it and how to use it?

Can someone give me practical examples in CommandParameters with MVVM that are not related to using third-party libraries (like MVVM Light), since I want to fully understand it before using existing libraries.

Thanks.

+4
source share
2 answers
 public class Command : ICommand { public event EventHandler CanExecuteChanged; Predicate<Object> _canExecute = null; Action<Object> _executeAction = null; public Command(Predicate<Object> canExecute, Action<object> executeAction) { _canExecute = canExecute; _executeAction = executeAction; } public bool CanExecute(object parameter) { if (_canExecute != null) return _canExecute(parameter); return true; } public void UpdateCanExecuteState() { if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs()); } public void Execute(object parameter) { if (_executeAction != null) _executeAction(parameter); UpdateCanExecuteState(); } } 

It is the base class for teams

And this is your Command property in ViewModel:

  private ICommand yourCommand; .... public ICommand YourCommand { get { if (yourCommand == null) { yourCommand = new Command( //class above p => true, // predicate to check "CanExecute" eg my_var != null p => yourCommandFunction(param1, param2)); } return yourCommand; } } 

in the XAML set Command binding Property like:

  <Button Command="{Binding Path=YourCommand}" .../> 
+4
source

Perhaps this article explains what you are looking for. I also had the same problem just a few minutes ago.

http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/76e6b583-edb1-4e23-95f6-7ad8510c0f88/pass-command-parameter-to-relaycommand.aspx

+1
source

Source: https://habr.com/ru/post/1332662/


All Articles