Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

c# - WPF Remove ScrollViewer from TreeView

I was wondering if it is possible to turn off the TreeView's ScrollViewer easily.

I have a UserControl with a Grid. One of the Cells has a few TreeViews inside a Stackpanel. The height of the Control sizes automatically depending on the height of the TreeViews, so there is no need for a scrollbar.

The problem is: I have a bunch of these in a ListBox with its own ScrollViewer, but when i am using the MouseWheel, scrolling stops when you are over a TreeView.

This is because the TreeView has its own ScrollViewer which steals the MouseWheel. I know this is probably possible by overriding the control template, but I hope there is an easier way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the technique described here: http://serialseb.blogspot.com/2007/09/wpf-tips-6-preventing-scrollviewer-from.html to prevent the mouse wheel events from being handled by the ScrollViewer. Add PreviewMouseWheel="HandlePreviewMouseWheel" to your TreeView and define HandlePreviewMouseWheel as:

private void HandlePreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    if (!e.Handled)
    {
        e.Handled = true;
        var eventArg = new MouseWheelEventArgs(
            e.MouseDevice, e.Timestamp, e.Delta);
        eventArg.RoutedEvent = UIElement.MouseWheelEvent;
        eventArg.Source = sender;
        var parent = ((Control)sender).Parent as UIElement;
        parent.RaiseEvent(eventArg);
    }
}

Changing the control template to not include a ScrollViewer isn't that hard, though, since the default template for TreeView is pretty simple, and most of the complexity is handling the ScrollViewer. Try doing this:

<TreeView.Template>
    <ControlTemplate TargetType="TreeView">
        <Border BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"
                SnapsToDevicePixels="true">
            <ItemsPresenter/>
        </Border>
    </ControlTemplate>
</TreeView.Template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...