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)
            );

    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();

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

    protected override void OnDetaching()
    {
        base.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:

<sdk:TreeView>
    <i:Interaction.Behaviors>
        <shemesh:TreeScrollBehavior ScrollDelta="50"/>
    </i:Interaction.Behaviors>
</sdk:TreeView>
Advertisements