处理页面 KeyUp 事件

Handling Page KeyUp event

我正在编写 C#/XAML UWP 应用程序。

我想在我的应用程序中处理整个页面的 KeyDown 事件。也就是说,无论页面上的哪个特定控件具有焦点(例如 TextBox、ListView 等),每当用户在该页面上按下某个键时,我都希望全局触发整个 Page KeyDown 事件。理论上这应该很简单——在页面导航到或加载时订阅 KeyDown 事件,例如:

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
     KeyDown += SettingsPage_KeyDown;
    }

实际上这并不适用于所有页面,即使是非常简单的页面也是如此,我不明白为什么。我连接了 Window.Current.CoreWindow.KeyDown 事件,它始终正常运行, 但我想知道 Page 的 KeyDown 事件出了什么问题。显然,这不起作用的原因可能有成百上千,但有没有共同点?我尝试将焦点设置到页面(程序化、键盘),但仍然 这个活动什么时候有效什么时候无效似乎没有规定。

我正在 Windows IoT 的应用程序中使用下一个代码,它有效:

public sealed partial class YourPage: Page
{
    public YourPage() //Constructor
    {
       this.InitializeComponent();

       //Add this line
       Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;    
    }

    void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        //todo
    }
}

您还可以在 XAML:

中添加 KeyDown 属性
<Page
x:Class="WESS1.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WESS1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" KeyDown="SettingsPage_KeyDown">

在代码隐藏文件中:

public sealed partial class SettingsPage: Page
{
    public SettingsPage() //Constructor
    {
       this.InitializeComponent();   
    }

    private void SettingsPage_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        // e.g. check the value of e.Key
    }
}