首页 > 解决方案 > 即使在用户控件中处理后,父页面的 keyDown 事件也会触发

问题描述

我有一个带有 CoreWindow_KeyDown 事件的 IndexPage。当我按下一个键时它会触发。这是正确的。如果我在包含 PreviewKeyDown/KeyDown 事件的用户控件上按下一个键,则 indexpage 的 CoreWindow_KeyDown 事件也会与用户控件的 PreviewKeyDown/KeyDown 事件一起触发。

UserControl_PreviewKeyDown, e.Handled = true
UserControl_KeyDown, e.Handled = true

如果 IndexPage 由用户控件处理,如何防止它触发 CoreWindow_KeyDown 事件?

标签: uwp

解决方案


即使在用户控件中处理后,父页面的 keyDown 事件也会触发

按照设计,将 e.Handled 设置为 trueUserControl_PreviewKeyDown不会禁用路由事件气泡到CoreWindow.

对于您的要求,由于PreviewKeyDown是控件需要聚焦的触发条件,我们可以声明布尔属性并在控件聚焦时将其设置为true。并使用此布尔属性禁用CoreWindow_KeyDown事件中的流程逻辑。

private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
    if (!_isFocus)
    {
        System.Diagnostics.Debug.WriteLine("---------!_isFocus-----------");
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("---------_isFocus-----------");
    }
}

private bool _isFocus;
private void MyCC_GettingFocus(UIElement sender, GettingFocusEventArgs args)
{
    _isFocus = true;
}

private void MyCC_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{
    _isFocus = false;
}

推荐阅读