Prevent Automatic Horizontal Scroll in TreeView

前端 未结 8 977
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 06:41

Whenever a node is selected in my treeview, it automatically does a horizontal scroll to that item. Is there a way to disable this?

8条回答
  •  无人及你
    2020-12-14 07:00

    @lena's solution of preserving vertical scrolling worked best for me. I've iterated on it a little bit:

        private void TreeViewItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
        {
            var treeViewItem = (TreeViewItem)sender;
            var scrollViewer = treeView.Template.FindName("_tv_scrollviewer_", treeView) as ScrollViewer;
    
            Point topLeftInTreeViewCoordinates = treeViewItem.TransformToAncestor(treeView).Transform(new Point(0, 0));
            var treeViewItemTop = topLeftInTreeViewCoordinates.Y;
            if (treeViewItemTop < 0
                || treeViewItemTop + treeViewItem.ActualHeight > scrollViewer.ViewportHeight
                || treeViewItem.ActualHeight > scrollViewer.ViewportHeight)
            {
                // if the item is not visible or too "tall", don't do anything; let them scroll it into view
                return;
            }
    
            // if the item is already fully within the viewport vertically, disallow horizontal scrolling
            e.Handled = true;
        }
    

    What this does is let the ScrollViewer scroll normally if the item isn't already in the viewport vertically. However for the actual "annoying" case (where the item is already visible), it sets e.Handled to true, thus preventing horizontal scrolling.

提交回复
热议问题