#1,082 – Adding CommandBindings to Individual UI Elements

Before using a routed command, you need to associated a particular command object with code for the Execute and CanExecute methods.  You do this by creating a CommandBinding object that binds the command to the code.  You then typically add that CommandBinding to the CommandBindings collection for the top-level window.

If you want to use the same command object, but bind it to different executable code for different UI elements, you can instead add the CommandBinding objects to the CommandBindings for individual elements.  In the code below, we create two different bindings for the ApplicationCommands.Open command.

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            btnA.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open,
                (sender, e) => { MessageBox.Show("Executing the Open command (version A)"); },
                (sender, e) => { e.CanExecute = CanOpenIsChecked; }));

            btnB.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open,
                (sender, e) => { MessageBox.Show("Executing the Open command (version B)"); },
                (sender, e) => { e.CanExecute = CanOpenIsChecked; }));
        }

1082-001
1082-002

Advertisement

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

One Response to #1,082 – Adding CommandBindings to Individual UI Elements

  1. Pingback: Dew Drop – May 29, 2014 (#1786) | Morning Dew

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: