Make WPF textbox as cut, copy and paste restricted

前端 未结 2 2076
温柔的废话
温柔的废话 2020-12-13 18:53

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

相关标签:
2条回答
  • 2020-12-13 19:22

    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;
         }
    }
    
    0 讨论(0)
  • 2020-12-13 19:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题