I propose a method which strengthens the one @Doc mentioned.
The following code @Doc mentioned will work since the KeyDown routed event is bubbled to the outermost Window
. Once Window
receives the KeyDown event bubbled from an inner element, Window
triggers any KeyDown event-handler registered to it, like this HandleKeyPress
.
private void UserControl_Loaded(object sender, RoutedEventArgs e) {
var window = Window.GetWindow(this);
window.KeyDown += HandleKeyPress;
}
private void HandleKeyPress(object sender, KeyEventArgs e) {
//Do work
}
But this +=
is risky, a programmer is more likely to forget to un-register the event-handler. Then memory leaking or some bugs will happen.
Here I suggest,
YourWindow.xaml.cs
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
// You need to have a reference to YourUserControlViewModel in the class.
YourUserControlViewModel.CallKeyDown(e);
// Or, if you don't like ViewModel, hold your user-control in the class then
YourUserControl.CallKeyDown(e);
}
YourUserControlViewModel.cs or YourUserControl.xaml.cs
public void CallKeyDown(KeyEventArgs e) {
//Do your work
}
There is no need to code in xaml.