开发者

A way to get a "button press event" for a WPF ScrollViewer control

My custom control uses a ScrollViewer and I want to determine when the user presses the horizontal scroll increment button while the control is already scrolled to the horizontal max.

The viewer contains a canvas and the idea is the canvas will extend if the user tries to scroll past its extent with the buttons.

ScrollViewer doesn't appear to have any events which relate to the buttons specifically and ScrollChanged is no use on its own since it doesn't trigger when the bar is at its extent.

.Net Reflector hasn't yielded much of use. The closest I can get is adding an开发者_开发知识库 event handler for mouseLeftButtonDown, I can see the viewers state but not how to determine whether the mouse event originated from the button.

Can anyone think of a way to do this?


You could try to get the buttons of the control via the VisualTree and attach a handler to their click events.

Edit: I wrote an extension method for getting items of visual tree via a path:

public static class ExtensionMethods
{
    public static DependencyObject GetVisualChildFromTreePath(this DependencyObject dpo, int[] path)
    {
        if (path.Length == 0) return dpo;
        List<int> newPath = new List<int>(path);
        newPath.RemoveAt(0);
        return VisualTreeHelper.GetChild(dpo, path[0]).GetVisualChildFromTreePath(newPath.ToArray());
    }
}

If your ScrollViewer is called sv you should be able to get the buttons like this:

RepeatButton button1 = sv.GetVisualChildFromTreePath(new int[] { 0, 2, 0, 0 }) as RepeatButton; //Up
RepeatButton button2 = sv.GetVisualChildFromTreePath(new int[] { 0, 2, 0, 2 }) as RepeatButton; //Down
RepeatButton button3 = sv.GetVisualChildFromTreePath(new int[] { 0, 3, 0, 0 }) as RepeatButton; //Left
RepeatButton button4 = sv.GetVisualChildFromTreePath(new int[] { 0, 3, 0, 2 }) as RepeatButton; //Right

Note: Buttons only exist if the respective scollbar is enabled. The extension method could probably improved in terms of performance by using other datatypes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜