Skip to content

InvokeCommandAction

branh edited this page Dec 4, 2018 · 1 revision

InvokeCommandBehavior causes a command to be invoked when a particular event occurs.

This behavior triggers a given Command with an optional CommandParameter whenever the specified trigger occurs. The behavior can be disabled by setting IsEnabled to false.

SampleCode

Xaml

<Button x:Name="button">
  <Behaviors:Interaction.Triggers>
    <Behaviors:EventTrigger EventName="Click" SourceObject="{Binding ElementName=button}">
      <Behaviors:InvokeCommandAction Command="{Binding ColorCommand}" CommandParameter="{Binding Grid.Background}" />
    </Behaviors:EventTrigger>
 </Behaviors:Interaction.Triggers>
</Button>

C#

public ChangeColorCommand ColorCommand { get; set; }

public MainWindow()
{
  this.ColorCommand = new ChangeColorCommand(this);
  InitializeComponent();
}

public class ChangeColorCommand : ICommand
{
  private Window window;
  public event EventHandler CanExecuteChanged;

  public ChangeColorCommand(Window window)
  {
    this.window = window;
  }

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

  public void Execute(object parameter)
  {
    this.window.Background = Brushes.DeepPink;
  }
}