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 cropped by the bottom of the control. So as I continue expanding items at the bottom of the tree, I have to keep manually scrolling down to see the new children. Anyone have a suggestion for how make it automatically scroll to show the newly expanded items?
相关问题
- VNC control for WPF application
- Use JS/jQuery to scroll a div's content that h
- WPF Binding from System.Windows.SystemParameters.P
- Jscrollpane - Fires a function when isAtBottom
- XAML: Applying styles to nested controls
You can use a simple EventSetter in TreeViewItem style to invoke an event handler when the item is selected. Then call BringIntoView for the item.
I modified Jared's answer in combination with the strategy from here: https://stackoverflow.com/a/42238409/2477582
The main advantage is that there aren't
n
calls of BringIntoView() forn
childs. There is only one call of BringIntoView for an area that covers all of the child's heights.Additionally, the purpose of the referred topic is realized as well. But this part may be removed, if unwanted.
The above solution works together with this:
This part takes care of toggling the elements at each click:
Finally the XAML part:
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.)
Use a dependency property on an IsSelected trigger:
Here's the code for the dependency property:
Thanks to itowlson's answer, here's the expanded event handler code that works for both of my trees