编程语言
首页 > 编程语言> > c# – 滚动到滚动视图中的选定Treeviewitem

c# – 滚动到滚动视图中的选定Treeviewitem

作者:互联网

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

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

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

解决方法:

我遇到了同样的问题,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;
    }
}

标签:c,wpf,treeview,scrollviewer
来源: https://codeday.me/bug/20190518/1130823.html