WPF Command execution and click event execution on buttons
I had to fix a bug today that was caused by the order of which a command and a click event was executed on a WPF button. I found no documentation of it so I thought I’d make a note of it.
If you have a WPF button like so:
<Button Command="{Binding Clear}" Click="ClearClicked" "></Button>
Then the click event gets executed first and the command is executed after.
Thus you can have the command as a separation layer between the ui and the presentation model. Having the command make the changes on the presentation layer, and have the click event handler to handle how the UI reacts to pressing the button.
If you for some reason need to have the UI execute after the command is executed, then I suggest a command class like the following:
using System;
/// <summary>
/// An ObservableCommand is a command where the execution of the command can be monitoried and thus acted upon;
/// </summary>
public abstract class ObservableCommand : ICommand {
///<summary>
/// The event fired when a command is executed;
///</summary>
public event EventHandler CommandExecuted = delegate { };
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null. </param>
public void Execute( object parameter ) {
ExecuteCommand( parameter );
CommandExecuted(this, EventArgs.Empty);
}
protected abstract void ExecuteCommand( object parameter );
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.
/// </param>
public virtual bool CanExecute( object parameter ) {
return true;
}
protected void RaiseCanExecuteChanged() {
CanExecuteChanged( this, EventArgs.Empty );
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged = delegate { };
}
So how to use this class?
First of, make sure your command class inherits from it like so:
/// <summary>
/// The save command
/// </summary>
internal class SaveCommand : ObservableCommand
Then hook on the CommandExecuted event to do your UI action accordingly:
Save.CommandExecuted += Save;
...
void Save( object sender, EventArgs e1 ) {
_textBox.AddText(string.Empty); _textBox.Focus();
}
To use this command in WPF is just like using any other command.
<button command="{Binding Save}" ...>