Прокрутка к выбранному Treeviewitem в scrollview

У меня есть scrollviewer обертывание treeview.

Я заполняю treeview программно (он не связывается), и разверните treeview до предопределенного treeviewitem. Это все хорошо работает.

Моя проблема состоит в том, что, когда дерево расширяется, я хотел бы scrollview, который порождает treeview для прокрутки к treeviewitem, который я просто развернул. Какие-либо идеи? - имеют в виду, что treeview не может иметь той же структуры каждый раз, когда это расширено, так, чтобы исключил просто хранение текущего положения прокрутки и сброс к этому...

5
задан Albert Oldfield 17 December 2009 в 15:40
поделиться

1 ответ

У меня была такая же проблема, когда 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
ответ дан 14 December 2019 в 13:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: