WPF TreeView - How to scroll so expanded branch is visible

前端 未结 6 1797
孤城傲影
孤城傲影 2020-12-14 16:56

When I expand items in my treeview so that scrolling is necessary, a scrollbar appears. However, it doesn\'t scroll down for the newly expanded branch of items - they get cr

6条回答
  •  生来不讨喜
    2020-12-14 17:36

    On the TreeView, handle the TreeViewItem.Expanded event (you can do this at the TreeView level because of event bubbling). In the Expanded handler, call BringIntoView on the TreeViewItem that raised the event.

    You may need a bit of trial and error to get hold of the TreeViewItem in your event handler code. I think (haven't checked) that the sender argument to your Expanded event handler will be the TreeView (since that's where the event handler is attached) rather than the TreeViewItem. And the e.Source or e.OriginalSource may be an element in the TreeViewItem's data template. So you may need to use VisualTreeHelper to walk up the visual tree to find the TreeViewItem. But if you use the debugger to inspect the sender and the RoutedEventArgs this should be trivial to figure out.

    (If you're able to get this working and want to bundle it up so you don't have to attach the same event handler to every TreeView, it should be easy to encapsulate it as an attached behaviour which will allow you to apply it declaratively, including via a Style.)

提交回复
热议问题