Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make WPF textbox as cut, copy and paste restricted

How can I make a WPF textbox cut, copy and paste restricted?

like image 393
Sauron Avatar asked Jun 02 '09 06:06

Sauron


People also ask

How do you make a TextBox non editable in WPF?

To prevent users from modifying the contents of a TextBox control, set the IsReadOnly attribute to true.

How do I prevent TextBox from copying?

The event. preventDefault() method stops the default action of an element from happening. You can use this method toprevent a TextBox control from Cut (Ctrl+X) , Copy (Ctrl+C) and Paste (Ctrl+V) .

How do I prevent TextBox from Pasteing?

The onpaste attribute lets us prevent pasting into the form. Adding the autocomplete attribute as well as preventing drag and drop into the element. If you want to avoid the on{event} code in the HTML, you can do it the cleaner way: myElement.


2 Answers

Cut, Copy and Paste are the common commands used any application,

<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"          ContextMenu="{x:Null}" /> 

in above textbox code we can restrict these commands in PrviewExecuted event of CommandManager Class

and in code behind add below code and your job is done

private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e) {      if (e.Command == ApplicationCommands.Copy ||          e.Command == ApplicationCommands.Cut  ||           e.Command == ApplicationCommands.Paste)      {           e.Handled = true;      } } 
like image 198
Prashant Cholachagudda Avatar answered Sep 21 '22 15:09

Prashant Cholachagudda


The commandName method will not work on a System with Japanese OS as the commandName=="Paste" comparision will fail. I tried the following approach and it worked for me. Also I do not need to disable the context menu manually.

In the XaML file:

<PasswordBox.CommandBindings>     <CommandBinding Command="ApplicationCommands.Paste"     CanExecute="CommandBinding_CanExecutePaste"></CommandBinding> </PasswordBox.CommandBindings> 

In the code behind:

private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e) {     e.CanExecute = false;     e.Handled = true; } 
like image 27
Debashis Panda Avatar answered Sep 21 '22 15:09

Debashis Panda