【问题标题】:UWP KeyRoutedEventArgs.handled Does Not Cancel Backspace KeyUWP KeyRoutedEventArgs.handled 不取消退格键
【发布时间】:2017-11-16 14:23:26
【问题描述】:

有没有办法在 UWP 中用KeyDownEvent 取消退格键?这个事件使用KeyRoutedEventArgs,所以没有SuppressKeyPress函数。

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

有这样的功能吗?

【问题讨论】:

  • e.Handled = true 应该可以工作,一定是有其他原因导致了这个问题,您能否发布完整的代码以获得进一步的帮助

标签: c# events uwp event-handling


【解决方案1】:

如果你有一个这样定义的文本框:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox KeyDown="TextBox_KeyDown"/>
</Grid>

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

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        e.Handled = true;
    }

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

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

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

XAML:

    <TextBox KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>

后面的代码:

    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;
    }

【讨论】:

  • 效果很好。谢谢。但是,有没有办法保存光标位置?我尝试添加一个选择更改函数和一个新变量,类似于您设置 currentText 的方式,但它总是突然恢复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
相关资源
最近更新 更多