#342 – Binding a Button to a Command
July 14, 2011 3 Comments
In WPF, the preferred method for executing some code when a button is clicked is to use a command. A command is an object that represents an action to be taken and is bound to a particular method that performs the action. The button is then associated with the command by setting its Command property.
Here’s an example.
<Button Content="Open" Command="ApplicationCommands.Open" />
ApplicationCommands.Open is a predefined command that is just a placeholder that you bind to some “open” logic in your application. You do this by adding a new CommandBinding object to the parent window’s CommandBindings collection.
You specify handlers for the Executed and CanExecute events of the command.
public MainWindow() { this.InitializeComponent(); CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute)); } public void Open_Executed(object sender, ExecutedRoutedEventArgs e) { // Open file here } public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; // Can we open file? }
Pingback: #1,078 – Defining a Command Binding Using Lambda Expressions | 2,000 Things You Should Know About WPF
Pingback: #1,079 – Executing a Command Programmatically | 2,000 Things You Should Know About WPF
Pingback: #1,085 – Input Bindings Don’t Require that Element Binds to Command | 2,000 Things You Should Know About WPF