KeyDown 事件绑定到用户控件

KeyDown event binding to user control

我目前正在使用 Caliburn.Micro 开发一个 WPF 项目,并希望将 KeyDown 事件绑定到 UserControl。如果 Window 打开并且用户按下任何按钮,它应该被触发。

<UserControl x:Class="Test.Views.AppView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:cal="http://www.caliburnproject.org"
         cal:Message.Attach="[Event KeyDown] = [TestMethod($executionContext)]" />

很遗憾,此代码无效。甚至可以将 Event 绑定到 UserControl 而不是绑定到 TextBoxButton 等特定控件吗?

如果此 UserControl 上的控件具有焦点,它将首先接收 KeyDown 事件并处理它。这将阻止 UserControl 接收它。

使用 PreviewKeyDown 捕获事件。 Preview... 事件正是针对这种情况。它们从根向上冒泡到子控件,而常规事件则向下。

如果冒泡和隧道应该停止,请不要忘记在处理程序的末尾设置 e.Handled = true;