Skip to content

InvokeCommandAction

Sean O edited this page Jul 18, 2018 · 2 revisions

The InvokeCommandAction action executes a specified ICommand on a specified target object when invoked.

Using the Behavior invokes the specified Command with the option to pass in arguments via CommandParameter

Sample Code

XAML

<Button x:Name="button1">
    <Interactivity:Interaction.Behaviors>
        <Interactions:EventTriggerBehavior EventName="Click" SourceObject="{Binding ElementName=button1}">
            <Interactions:InvokeCommandAction Command="{Binding UpdateCountCommand}"/>
        </Interactions:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
</Button>

C#

public class SampleCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        CanExecuteChanged(null, null);
    }
}

public ICommand UpdateCountCommand { get; set; }

public InvokeCommandControl()
{
    this.InitializeComponent();
    UpdateCountCommand = new SampleCommand();

    this.UpdateCountCommand.CanExecuteChanged += UpdateCountCommand_CanExecuteChanged;

    this.DataContext = this;
}

private void UpdateCountCommand_CanExecuteChanged(object sender, EventArgs e)
{
    Count++;
    OnPropertyChanged(nameof(Count));
}

private void OnPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}