#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"
                 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;

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

3 Responses to #1,093 – Intercepting a Command Before It Executes

  1. Pingback: Dew Drop – June 13, 2014 (#1797) | Morning Dew

  2. Chris says:

    Looks like a copy/paste error… instead of the 2nd code sample, you have the 1st code sample repeated.

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: