#1,081 – Adding CommandBinding to Top-Level CommandBindings

In the example below, we bind the ApplicationCommands.Open command to some custom code by adding a CommandBinding instance to the top-level window’s CommandBindings property.

        public MainWindow()
            this.DataContext = this;

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

We can now bind the Command property of any UI element under the top-level window to the ApplicationCommands.Open command.  Below, we bind two different buttons to the Open command.  Clicking on either button will result in execution of the same lambda expression.

<Window x:Class="WpfApplication1.MainWindow"
        Title="Commands" Width="320" Height="220">

        <Button Content="Open A" Command="ApplicationCommands.Open"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />
        <Button Content="Open B" Command="ApplicationCommands.Open"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />
        <CheckBox Content="Can Open" IsChecked="{Binding CanOpenIsChecked}"



About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,081 – Adding CommandBinding to Top-Level CommandBindings

  1. Pingback: Dew Drop – May 28, 2014 (#1785) | Morning Dew

  2. Pingback: #1,082 – Adding CommandBindings to Individual UI Elements | 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: