I have a WPF application where I have defined custom commands that use the key gestures Ctrl + ← and Ctrl + →. My window has a TextBox
and a ScrollViewer
and when the TextBox
has focus Ctrl + ← and Ctrl + → move the cursor to the beginning of the next or previous word, which is fine.
But on the ScrollViewer
it makes the horizontal scroll move as if I had pressed just ← or → . What's the easiest way to allow the Ctrl + ← and Ctrl + → events to bubble up from my ScrollViewer
to the Window where the Command
is defined?
So I got this working by doing the following
public class MyScrollViewer : ScrollViewer
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
if (e.Key == Key.Left || e.Key == Key.Right)
return;
}
base.OnKeyDown(e);
}
}
I think the trick is to understand that the event starts at the top and works it's way down. Then on the way back up each "layer" checks the Handled boolean and if it isn't set to true it will determine if it will do something and set it if it does. I needed to short circuit this behavior for my shortcuts so that Handled would still be false when it made it's way back up to the Window level.
You must override ScrollViewer
's PreviewKeyDown
event and set e.Handled = true
and pass on the event to parent using something like (this.Parent as FrameworkElement).RaiseEvent(e);
if the keys pressed were one of the key combination you assigned to your commands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With