如何在WPF中禁止TextBox中的剪切,复制和粘贴操作?

时间:2022-09-28 23:04:43

I want to suppress Cut, Copy and Paste operations in Text Box.

我想在文本框中抑制剪切,复制和粘贴操作。

I don't want user to do any of these operations through keyboard or from default context menu in the text box .

我不希望用户通过键盘或文本框中的默认上下文菜单执行任何这些操作。

Please let me know how can I restrict these operations?

请让我知道如何限制这些操作?

1 个解决方案

#1


8  

You can do this pretty easily using the CommandManager.PreviewCanExecute routed event. In your XAML, you would put the following on your TextBox element. This will apply to CTL+V, etc as well as the context menu or any buttons that you may have mapped to those commands so it's very effective.

您可以使用CommandManager.PreviewCanExecute路由事件轻松完成此操作。在您的XAML中,您将把以下内容放在TextBox元素上。这将适用于CTL + V等,以及上下文菜单或您可能已映射到这些命令的任何按钮,因此它非常有效。

<TextBox CommandManager.PreviewCanExecute="HandleCanExecute" />

Then in your code-behind, add a HandleCanExecute method that disables the commands.

然后在您的代码隐藏中,添加一个禁用命令的HandleCanExecute方法。

private void HandleCanExecute(object sender, CanExecuteRoutedEventArgs e) {

    if ( e.Command == ApplicationCommands.Cut ||
         e.Command == ApplicationCommands.Copy ||
         e.Command == ApplicationCommands.Paste ) {

        e.CanExecute = false;
        e.Handled = true;

    }

}

#1


8  

You can do this pretty easily using the CommandManager.PreviewCanExecute routed event. In your XAML, you would put the following on your TextBox element. This will apply to CTL+V, etc as well as the context menu or any buttons that you may have mapped to those commands so it's very effective.

您可以使用CommandManager.PreviewCanExecute路由事件轻松完成此操作。在您的XAML中,您将把以下内容放在TextBox元素上。这将适用于CTL + V等,以及上下文菜单或您可能已映射到这些命令的任何按钮,因此它非常有效。

<TextBox CommandManager.PreviewCanExecute="HandleCanExecute" />

Then in your code-behind, add a HandleCanExecute method that disables the commands.

然后在您的代码隐藏中,添加一个禁用命令的HandleCanExecute方法。

private void HandleCanExecute(object sender, CanExecuteRoutedEventArgs e) {

    if ( e.Command == ApplicationCommands.Cut ||
         e.Command == ApplicationCommands.Copy ||
         e.Command == ApplicationCommands.Paste ) {

        e.CanExecute = false;
        e.Handled = true;

    }

}