我有一个包装树视图的滚动查看器。
我以编程方式填充树视图(未绑定),并将树视图扩展为预定的树视图项。这一切都很好。
我的问题是,当树扩展时,我希望作为树视图的父级的滚动视图滚动到我刚刚扩展的树视图项。有任何想法吗?- 请记住,树视图每次展开时可能没有相同的结构,因此排除了仅存储当前滚动位置并重置为...
我有一个包装树视图的滚动查看器。
我以编程方式填充树视图(未绑定),并将树视图扩展为预定的树视图项。这一切都很好。
我的问题是,当树扩展时,我希望作为树视图的父级的滚动视图滚动到我刚刚扩展的树视图项。有任何想法吗?- 请记住,树视图每次展开时可能没有相同的结构,因此排除了仅存储当前滚动位置并重置为...
我遇到了同样的问题,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;
}
}
Jason 的 ScrollViewer 技巧是将 TreeViewItem 移动到特定位置的好方法。
但是有一个问题:在 MVVM 中,您无法访问视图模型中的 ScrollViewer。无论如何,这是一种方法。如果你有一个 TreeViewItem,你可以沿着它的可视化树向上走,直到你到达嵌入的 ScrollViewer:
// Get the TreeView's ScrollViewer
DependencyObject parent = VisualTreeHelper.GetParent(selectedTreeViewItem);
while (parent != null && !(parent is ScrollViewer))
{
parent = VisualTreeHelper.GetParent(parent);
}