#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?