Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to ICommand

Tags:

c#

wpf

I have a simple button that uses a command when executed, this is all working fine but I would like to pass a text parameter when the button is clicked.

I think my XAML is ok, but I'm unsure how to edit my RelayCommand class to receive a parameter:

<Button x:Name="AddCommand" Content="Add" 
    Command="{Binding AddPhoneCommand}"
    CommandParameter="{Binding Text, ElementName=txtAddPhone}" />
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();
    }
}
like image 597
Michael Harper Avatar asked Oct 28 '12 20:10

Michael Harper


People also ask

How do you pass a command parameter in WPF MVVM?

A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.

What is ICommand xamarin?

The Command Class Because ICommand is part of Microsoft Windows, it has been used for years with Windows MVVM applications. Using a Windows class that implements ICommand allows you to share your ViewModels between Windows applications and Xamarin. Forms applications. If sharing ViewModels between Windows and Xamarin.

What is RelayCommand WPF?

The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.


1 Answers

Change Action to Action<T> so that it takes a parameter (probably just Action<object> is easiest).

private readonly Action<object> _handler;

And then simply pass it the parameter:

public void Execute(object parameter)
{
    _handler(parameter);
}
like image 93
McGarnagle Avatar answered Sep 18 '22 14:09

McGarnagle