WPF TreeView - How to scroll so expanded branch is visible WPF TreeView - How to scroll so expanded branch is visible wpf wpf

WPF TreeView - How to scroll so expanded branch is visible


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.

<TreeView > <TreeView.ItemContainerStyle>   <Style TargetType="{x:Type TreeViewItem}">     <EventSetter Event="Selected" Handler="TreeViewSelectedItemChanged" />   </Style> </TreeView.ItemContainerStyle></TreeView>private void TreeViewSelectedItemChanged(object sender, RoutedEventArgs e){    TreeViewItem item = sender as TreeViewItem;    if (item != null)    {        item.BringIntoView();        e.Handled = true;      }}


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:

<Style TargetType="{x:Type TreeViewItem}"> <Style.Triggers>  <Trigger Property="IsSelected" Value="True">    <Setter Property="commands:TreeViewItemBehavior.BringIntoViewWhenSelected" Value="True" />  </Trigger></Style.Triggers>

Here's the code for the dependency property:

public static bool GetBringIntoViewWhenSelected(TreeViewItem treeViewItem){  return (bool)treeViewItem.GetValue(BringIntoViewWhenSelectedProperty);}public static void SetBringIntoViewWhenSelected(TreeViewItem treeViewItem, bool value){  treeViewItem.SetValue(BringIntoViewWhenSelectedProperty, value);}public static readonly DependencyProperty BringIntoViewWhenSelectedProperty =    DependencyProperty.RegisterAttached("BringIntoViewWhenSelected", typeof(bool),    typeof(TreeViewItemBehavior), new UIPropertyMetadata(false, OnBringIntoViewWhenSelectedChanged));static void OnBringIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e){  TreeViewItem item = depObj as TreeViewItem;  if (item == null)    return;  if (e.NewValue is bool == false)    return;  if ((bool)e.NewValue)    item.BringIntoView();}