Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make scrollviewer not capture control left and control right in WPF

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?

like image 715
juharr Avatar asked Jun 20 '10 23:06

juharr


2 Answers

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.

like image 151
juharr Avatar answered Nov 04 '22 20:11

juharr


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.

like image 26
decyclone Avatar answered Nov 04 '22 19:11

decyclone