#1,094 – Disabling Editing Operations in a TextBox

You can disable the cut/copy/paste features in a TextBox by handling the CommandManager.PreviewCanExecute event and checking for the associated editing commands.

TextBox has implicit command bindings to support cut, copy, and paste commands.  When the user executes one of these commands, using the context menu or a keyboard shortcut, the associated routed command is executed, with the TextBox as the source.  You can short-circuit the command by intercepting PreviewCanExecute and making sure that CanExecute returns false.

Markup:
        <TextBox Name="txtSomeText"
                 CommandManager.PreviewCanExecute="txtSomeText_PreviewCanExecute"
                 Width="220" Height="25" Margin="10"/>

Code-behind:

        private void txtSomeText_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if ((e.Command == ApplicationCommands.Cut) ||
                (e.Command == ApplicationCommands.Copy) ||
                (e.Command == ApplicationCommands.Paste))
            {
                e.Handled = true;
                e.CanExecute = false;
            }
        }

The editing functions are now disabled. The context menu in the TextBox shows the commands greyed out and corresponding keyboard shortcuts do nothing.

1094-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,094 – Disabling Editing Operations in a TextBox

  1. Pingback: Dew Drop – June 16, 2014 (#1798) | Morning Dew

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: