views:

29

answers:

2

I have a WPF application where I have defined custom commands that use the key gestures Ctrl-Left and Ctrl-Right. My window has a TextBox and a ScrollViewer and when the TextBox has focus Ctrl-Left and Ctrl-Right 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 Left or Right. What's the easiest way to allow the Ctrl-Left and Ctrl-Right events to bubble up from my ScrollViewer to the Window where the Command is defined?

A: 

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.

decyclone
A: 

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.

juharr