在 wpf 文本框中限制按键

Restrict keypress in wpf textbox

我在 WPF 中有 TextBox,我只需要通过粘贴 (ctrl +v) 而不是通过键入来填充框。所以我需要限制除 ctrl+v 之外的整个按键。由于 WPF 没有按键事件,我面临限制按键的问题

如果您不允许 Right Click + Paste,但只允许 Ctrl + V,我会简单地检查是否按下了 Ctrl 键修饰符并阻止其他一切。

您可以将此 Key_Down 处理程序添加到文本框:

  private void textBox1_KeyDown(object sender, KeyEventArgs e)
   {
      if (e.Modifiers == Keys.Control && e.Key==Key.V)
       {
         //Logic here
       }
      else
        e.handled=true;
   }

所以试试这个:

 myTextBox.KeyDown += new KeyEventHandler(myTextBox_KeyDown);

 private void myTextBox_KeyDown(object sender, KeyEventArgs e)
 {
      if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
      {
            input = myTextBox.Text;
      }
      else
      {
            input = "";
      }

  }

使用 WPF 样式并使用 ApplicationCommands.Paste 并将文本框设置为只读。

<TextBox IsReadOnly="True" Name="Policy_text">
   <TextBox.CommandBindings>
       <CommandBinding Command="ApplicationCommands.Paste" CanExecute="PasteCommand_CanExecute" Executed="PasteCommand_Executed" />
   </TextBox.CommandBindings>
</Textbox>

在后面的代码中

private void PasteCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = Clipboard.ContainsText();
    }

private void PasteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Policy_text.Paste();
    }