#342 – Binding a Button to a Command

In WPF, the preferred method for executing some code when a button is clicked is to use a commandA 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()

            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?

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #342 – Binding a Button to a Command

  1. Pingback: #1,078 – Defining a Command Binding Using Lambda Expressions | 2,000 Things You Should Know About WPF

  2. Pingback: #1,079 – Executing a Command Programmatically | 2,000 Things You Should Know About WPF

  3. Pingback: #1,085 – Input Bindings Don’t Require that Element Binds to Command | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: