C# 将 WPF 文本框限制为剪切、复制和粘贴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/938145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:46:49  来源:igfitidea点击:

Make WPF textbox as cut, copy and paste restricted

c#wpfwpf-controls

提问by Sauron

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

如何限制 WPF 文本框的剪切、复制和粘贴?

采纳答案by Prashant Cholachagudda

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

在上面的文本框代码中,我们可以在 CommandManager 类的 PrviewExecuted 事件中限制这些命​​令

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

回答by Debashis Panda

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.

commandName 方法不适用于具有日语操作系统的系统,因为 commandName=="Paste" 比较将失败。我尝试了以下方法,它对我有用。此外,我不需要手动禁用上下文菜单。

In the XaML file:

在 XaML 文件中:

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