How to disable Copy and Paste for a control in WPF

By default all the TextBox’s (an other controls) in WPF have a default ContextMenu that allows copy, paste and cut. You can disable this menu by setting this property as “{x:Null}”, but the keys associated with the menu options still work. In order to disable this commands we can use the DataObject class, which have handlers to attach any DepencencyObject in case on Copy or Paste:

DataObject.AddPastingHandler(control, this.OnCancelCommand);

DataObject.AddCopyingHandler(control, this.OnCancelCommand);

Finally in the event handler we need to cancel the current command:

private void OnCancelCommand(object sender, DataObjectEventArgs e)

{

    e.CancelCommand();

}

The CancelCommand method will cancel any ApplicationCommand.Copy, ApplicationCommand.Paste and ApplicationCommand.Cut sent over the control.

Published Tuesday, April 28, 2009 5:40 PM by marianor
Filed under:

Comments

# How to disable Copy and Paste for a control in WPF - Unknown Recipes

Pingback from  How to disable Copy and Paste for a control in WPF - Unknown Recipes

# re: How to disable Copy and Paste for a control in WPF

Wednesday, September 02, 2009 8:23 AM by tyllendal

I also found, if you'd like to keep the disabling in the xaml, you could use the following:

<TextBox.InputBindings>

               <KeyBinding Command="ApplicationCommands.NotACommand" Key="V" Modifiers="Control" />

           </TextBox.InputBindings>

Leave a Comment

(required) 
(required) 
(optional)
(required)