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

Alb*_*eld 5 c# wpf treeview scrollviewer

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

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

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

Jas*_*son 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);
Run Code Online (Sandbox Code Playgroud)

这是 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;
    }
}
Run Code Online (Sandbox Code Playgroud)