WPF TextBox - 如何捕获和处理 Backspace 和 Delete 事件

WPF TextBox - How to trap and deal with Backspace and Delete events

我试图在用户 select 并删除 wpf 文本框中的文本时警告用户。 我能够使用 previewkeydown 事件捕获删除事件,但它取消了删除事件。即使您在下面的代码中按确定 - 也不会发生删除。我错过了一些东西...

private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Delete)
            {
                var textbox = (TextBox)sender;
                if (textbox.SelectionLength > 1)
                {
                    var result = MessageBox.Show("Delete selected?", "MyApp", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        e.Handled = true;
                       
                    }
                }
            }
        }

This does not seem to be the proper usage of the PreviewKeyDown event handler。该处理程序似乎旨在重定向 non-standard 输入键事件以执行自定义行为。不考虑删除键 non-standard/special.

你的当前代码的想法是正确的,但现在你只需要实际删除文本框中的文本。

private void TextBox_KeyDownHandler(object sender, KeyEventArgs e)
{
    switch(e.KeyCode)
    {
       case Keys.Delete:
            if (sender is TextBox tb)
            {
                if(tb.SelectionLength > 1 && MessageBox.Show("Delete?", "MyApp", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    tb.SelectedText = "";
                }
            }
            e.Handled = true;
            break;
    }
}

最后,确保您确实订阅了您的处理程序

public MainWindow()
{
   InitializeComponent();
   MyTextBox.KeyDown += new KeyEventHandler(TextBox_KeyDownHandler);
}