Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress Cut, Copy and Paste Operations in TextBox in WPF?

I want to suppress Cut, Copy and Paste operations in Text Box.

I don't want user to do any of these operations through keyboard or from default context menu in the text box .

Please let me know how can I restrict these operations?

like image 406
Ashish Ashu Avatar asked Jun 16 '10 06:06

Ashish Ashu


1 Answers

You can do this pretty easily using the CommandManager.PreviewCanExecute routed event. In your XAML, you would put the following on your TextBox element. This will apply to CTL+V, etc as well as the context menu or any buttons that you may have mapped to those commands so it's very effective.

<TextBox CommandManager.PreviewCanExecute="HandleCanExecute" />

Then in your code-behind, add a HandleCanExecute method that disables the commands.

private void HandleCanExecute(object sender, CanExecuteRoutedEventArgs e) {

    if ( e.Command == ApplicationCommands.Cut ||
         e.Command == ApplicationCommands.Copy ||
         e.Command == ApplicationCommands.Paste ) {

        e.CanExecute = false;
        e.Handled = true;

    }

}
like image 64
Josh Avatar answered Sep 22 '22 16:09

Josh