#344 – The CommandBinding CanExecute Event Determines Whether a Button is Enabled

When you associate a button’s Command property with a CommandBinding object,and bind the CommandBinding object to both Executed and CanExecute handlers, the Button control will automatically toggle between enabled/disabled, depending on the code in the CanExecute method.

Suppose we create two buttons, binding them to open/close commands.

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Button Content="Open" Command="ApplicationCommands.Open"
                VerticalAlignment="Center" Padding="10,5" Margin="5"/>
        <Button Content="Close" Command="ApplicationCommands.Close"
                VerticalAlignment="Center" Padding="10,5" Margin="5"/>
    </StackPanel>

Then we create a CommandBinding and associated handlers.

		public MainWindow()
		{
			this.InitializeComponent();

            CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, Close_Executed, Close_CanExecute));
        }

        private bool isOpen = false;

        public void Open_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Open");
            isOpen = true;
        }

        public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = !isOpen;
        }

        public void Close_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Close");
            isOpen = false;
        }

        public void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = isOpen;
        }

The buttons will now automatically be enabled/disabled, depending on the value of isOpen.

Follow

Get every new post delivered to your Inbox.

Join 356 other followers