UWP KeyRoutedEventArgs.handled 不会取消退格键

Ori*_*n31 0 c# events event-handling uwp

有没有办法用KeyDownEventUWP 中的a 取消退格键?此事件使用KeyRoutedEventArgs,因此没有SuppressKeyPress功能。

event.Handled = true没有帮助;它只会阻止从同一按键快速连续多次调用该事件。

有这样的功能吗?

Mik*_*nen 5

如果您有一个像这样定义的 TextBox:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox KeyDown="TextBox_KeyDown"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

在 KeyDown 事件中,如果您每次都设置 Handled = true,则用户无法输入任何内容:

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        e.Handled = true;
    }
Run Code Online (Sandbox Code Playgroud)

但是正如您所提到的,如果您检查 Back-key 并设置 Handled = true,则它不起作用:用户仍然可以使用退格键。所以这行不通。

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            e.Handled = true;
            return;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果您调试代码,您可以看到在执行事件处理程序时该字符已经消失。您必须使用其他事件来解决此问题。这是一种选择:

XAML:

    <TextBox KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>
Run Code Online (Sandbox Code Playgroud)

后面的代码:

    private string currentText;
    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            if (string.IsNullOrWhiteSpace(currentText))
                return;

            ((TextBox)sender).Text = currentText;
            ((TextBox)sender).SelectionStart = currentText.Length;
            ((TextBox)sender).SelectionLength = 0;
        }
    }

    private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        currentText = ((TextBox)sender).Text;
    }
Run Code Online (Sandbox Code Playgroud)