#1,093 – Intercepting a Command Before It Executes

When a command that is bound to an element executes, it executes some code.  The code is linked to the command as part of the command binding.  In some cases, you don’t have access to this code.  The TextBox control, for example, has built-in commands for cut/copy/paste features.

You can intercept a command that is about to be executed on an element by defining a handler for the PreviewExecuted event.

        <TextBox Name="txtSomeText"
                 CommandManager.PreviewExecuted="txtSomeText_PreviewExecuted"
                 Width="220" Height="25" Margin="10"/>

In the body of the PreviewExecuted handler, you can determine what command is being executed.  You can cancel the execution by setting the Handled property to true.  In the example below, we prohibit Paste functionality in the TextBox.

        private void txtSomeText_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == ApplicationCommands.Paste)
            {
                e.Handled = true;
            }
        }
Advertisements