Silverlight: TreeView Scroll behavior

The tree control (TreeView) of Silverlight have a problem with scrolling – it scroll only when the mouse is over an item. if you try to scroll when the mouse is over an empty space… nothing will happen.
see this stackoverflow issue.

i came up with a simple solution that do not require any intervention in templates.
a simple behavior for your misbehaving tree view:

public class TreeScrollBehavior : Behavior<TreeView>

    #region ScrollDelta (DependencyProperty)

    public double ScrollDelta
        get { return (double)GetValue(ScrollDeltaProperty); }
        set { SetValue(ScrollDeltaProperty, value); }
    public static readonly DependencyProperty ScrollDeltaProperty =
        DependencyProperty.Register("ScrollDelta", typeof(double), typeof(TreeScrollBehavior),
            new PropertyMetadata(20.0)


    protected override void OnAttached()

        AssociatedObject.AddHandler(UIElement.MouseWheelEvent, new MouseWheelEventHandler(OnMouseWheel), true);

    protected override void OnDetaching()

        AssociatedObject.MouseWheel -= OnMouseWheel;

    private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        e.Handled = true;
        var delta = ScrollDelta;
        if (e.Delta > 0)
            delta = 0 - ScrollDelta;
        var scroll = AssociatedObject.GetScrollHost();
        scroll.ScrollToVerticalOffset(scroll.VerticalOffset + delta);

example use:

        <shemesh:TreeScrollBehavior ScrollDelta="50"/>

One Response to Silverlight: TreeView Scroll behavior

  1. Jwood says:

    Thank you! I was about to write this myself. No need any more.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: