如何使 WPF 文本框剪切、复制和粘贴受到限制?
剪切、复制和粘贴是任何应用程序中使用的常用命令。
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"
ContextMenu="{x:Null}" />
在上面的文本框代码中,我们可以在 CommandManager 类的 PreviewExecuted 事件中限制这些命令。
在后面的代码中添加以下代码,您的工作就完成了。
private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Copy ||
e.Command == ApplicationCommands.Cut ||
e.Command == ApplicationCommands.Paste)
{
e.Handled = true;
}
}
commandName 方法在日语操作系统上不起作用,因为 commandName=="Paste" 比较将失败。我尝试了以下方法,它对我有用。另外,我不需要手动禁用上下文菜单。
在 XaML 文件中:
<PasswordBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
CanExecute="CommandBinding_CanExecutePaste"></CommandBinding>
</PasswordBox.CommandBindings>
在后面的代码中:
private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}