我有一个包含 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/