c# - 在 ScrollView 中滚动到选定的 Treeviewitem

标签 c# wpf treeview scrollviewer

我有一个包含 TreeView 的滚动查看器。

我以编程方式填充 TreeView (未绑定(bind)),并将 TreeView 展开为预定的 TreeView 项。一切正常。

我的问题是,当树展开时,我希望作为 treeview 父级的 scrollview 滚动到我刚刚展开的 treeviewitem。有任何想法吗? - 请记住, TreeView 每次展开时可能都不具有相同的结构,因此排除了仅存储当前滚动位置并重置为该位置的可能性...

最佳答案

我遇到了同样的问题,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# - 在 ScrollView 中滚动到选定的 Treeviewitem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1922607/

相关文章:

c# - MVVM Light - RaisePropertyChanged 不起作用

javascript - 如何将 JavaScript 变量设置为 ASP.NET session ?

wpf - 绑定(bind)属性中的“自动”值 'width'

file - 如何加载显示在 Kendo Treeview 中的文件

button - 如何在 TreeView 标题中靠近 "Create"和 "Import"按钮 Odoo 8 添加按钮?

wpf - CollectionViewSource : TreeView not updating, ViewModel 看起来不错

c# - 使用 Entity Framework 将 T-SQL 转换为 LINQ

c# - 将导航属性映射到存储过程

wpf - MVVM - 绑定(bind)和更新方法

wpf - 复制不适用于数据网格模板列?