#1,078 – Defining a Command Binding Using Lambda Expressions

Recall that commands in WPF are objects that you bind UI elements to and that are in turn bound to code for executing the command and for knowing whether a command can be executed.

Below is an example that sets up a command binding using lambda expressions.

    <Window.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Open" Command="ApplicationCommands.Open"/>
        </ContextMenu>
    </Window.ContextMenu>

    <StackPanel>
        <Button Content="Open" Command="ApplicationCommands.Open"
                Margin="10" HorizontalAlignment="Center" />
        <CheckBox Content="Can Open" IsChecked="{Binding CanOpenIsChecked}"
                  Margin="10"/>
    </StackPanel>

We set up the command binding in the window’s constructor.

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

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

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        public bool CanOpenIsChecked { get; set; }
    }

1078-001
1078-002

Advertisement

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

3 Responses to #1,078 – Defining a Command Binding Using Lambda Expressions

  1. Pingback: Dew Drop – May 22, 2014 (#1782) | Morning Dew

  2. Tousif says:

    Can we implement INotifyPropertychange on auto property
    public bool CanOpenIsChecked { get; set; }

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: