在滚动视图中滚动到选定的Treeviewitem

时间:2009-12-17 15:40:52

标签: c# wpf treeview scrollviewer

我有一个包含树视图的scrollviewer。

我以编程方式填充树视图(它没有绑定),并将树视图展开为预定的treeviewitem。一切正常。

我的问题是,当树展开时,我想滚动视图,父树视图滚动到我刚刚展开的树视图。有任何想法吗? - 请记住,树视图每次展开时可能没有相同的结构,因此排除存储当前滚动位置并重置为该结构...

2 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,TreeView没有滚动到所选项目。

我做的是,在将树展开到选定的TreeViewItem之后,我调用了Dispatcher Helper方法以允许UI更新,然后在所选项目上使用TransformToAncestor来查找其在ScrollViewer中的位置。这是代码:

    // Allow UI Rendering to Refresh
    DispatcherHelper.WaitForPriority();

    // Scroll to selected Item
    TreeViewItem tvi = myTreeView.SelectedItem as TreeViewItem;
    Point offset = tvi.TransformToAncestor(myScroll).Transform(new Point(0, 0));
    myScroll.ScrollToVerticalOffset(offset.Y);

这是DispatcherHelper代码:

public class DispatcherHelper
{
    private static readonly DispatcherOperationCallback exitFrameCallback = ExitFrame;

    /// <summary>
    /// Processes all UI messages currently in the message queue.
    /// </summary>
    public static void WaitForPriority()
    {
        // Create new nested message pump.
        DispatcherFrame nestedFrame = new DispatcherFrame();

        // Dispatch a callback to the current message queue, when getting called,
        // this callback will end the nested message loop.
        // The priority of this callback should be lower than that of event message you want to process.
        DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
            DispatcherPriority.ApplicationIdle, exitFrameCallback, nestedFrame);

        // pump the nested message loop, the nested message loop will immediately
        // process the messages left inside the message queue.
        Dispatcher.PushFrame(nestedFrame);

        // If the "exitFrame" callback is not finished, abort it.
        if (exitOperation.Status != DispatcherOperationStatus.Completed)
        {
            exitOperation.Abort();
        }
    }

    private static Object ExitFrame(Object state)
    {
        DispatcherFrame frame = state as DispatcherFrame;

        // Exit the nested message loop.
        frame.Continue = false;
        return null;
    }
}

答案 1 :(得分:2)

Jason的ScrollViewer技巧是将TreeViewItem移动到特定位置的好方法。

但有一个问题:在MVVM中,您无法访问视图模型中的ScrollViewer。无论如何,这是一种方法。如果你有一个TreeViewItem,你可以走到它的可视树,直到你到达嵌入式ScrollViewer:

// Get the TreeView's ScrollViewer
DependencyObject parent = VisualTreeHelper.GetParent(selectedTreeViewItem);
while (parent != null && !(parent is ScrollViewer))
{
    parent = VisualTreeHelper.GetParent(parent);
}