views:

1794

answers:

2

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

+2  A: 

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

<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"  />

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)
{
     var commandName = ((System.Windows.Input.RoutedUICommand)(e.Command)).Text;
     if (commandName == "Copy" || commandName == "Cut" || commandName == "Paste")
          e.Handled = true;
}
Prashant
I think I also need to set the contextmenu to null.
Sauron
Its perfect, if u disable context menu
Prashant
A: 

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;
}