Scroll to selected Treeviewitem in scroll

I have a scrollviewer wrapping a treeview.

I fill the tree image programmatically (it is not attached) and expands the tree structure to the specified tree element. Everything works perfectly.

My problem is that when the tree expands, I need the scrollview to give birth to the tree in order to scroll to the tree that I just expanded. Any ideas? - keep in mind that the tree structure may not have the same structure every time it expands, therefore it excludes just saving the current scroll position and its reselling ...

+5
source share
2 answers

, TreeView .

, TreeViewItem Dispatcher Helper, , 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;
    }
}
+4

Jason ScrollViewer - TreeViewItem .

: MVVM ScrollViewer . , . TreeViewItem, , ScrollViewer:

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

All Articles