#1,079 – Executing a Command Programmatically

You normally bind the Command property of a user interface element to a routed command to have the command automatically executed when the user interacts with the user interface element.

You can also execute commands programmatically by calling their Execute method.  Note that the command will do nothing if CanExecute is returning false.

        <Button Content="Do Something" Click="Button_Click"
                Margin="10" HorizontalAlignment="Center"/>
        <CheckBox Content="Can Open" IsChecked="{Binding CanOpenIsChecked}"
                  Margin="10"/>
    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; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Execute command programmatically
            if (ApplicationCommands.Open.CanExecute(null, null))
                ApplicationCommands.Open.Execute(null, null);
            else
                MessageBox.Show("No no no!");
        }
    }

1079-001
 

Advertisement