将 WPF Listview 滚动到特定行 [英] Scroll WPF Listview to specific line

查看:73
本文介绍了将 WPF Listview 滚动到特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WPF,类似浏览器的应用程序.
我有一个包含 ListView 的页面.调用 PageFunction 后,我将一行添加到 ListView,并希望将新行滚动到视图中:

WPF, Browserlike app.
I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view:

  ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
  if (item != null)
    ScrollIntoView(item);

这有效.只要新行在视图中,该行就会像应有的那样获得焦点.

This works. As long as the new line is in view the line gets the focus like it should.

问题是,当线条不可见时,事情就不起作用了.
如果该行不可见,则生成的行没有 ListViewItem,因此 ItemContainerGenerator.ContainerFromIndex 返回 null.

Problem is, things don't work when the line is not visible.
If the line is not visible, there is no ListViewItem for the line generated, so ItemContainerGenerator.ContainerFromIndex returns null.

但没有该项目,我如何将行滚动到视图中?有没有办法在不需要 ListViewItem 的情况下滚动到最后一行(或任何地方)?

But without the item, how do I scroll the line into view? Is there any way to scroll to the last line (or anywhere) without needing an ListViewItem?

推荐答案

我认为这里的问题是如果该行不可见,则尚未创建 ListViewItem.WPF 按需创建 Visible.

I think the problem here is that the ListViewItem is not created yet if the line is not visible. WPF creates the Visible on demand.

所以在这种情况下,您可能会为该项目获得 null ,是吗?(根据你的评论,你做)

So in this case you probably get null for the item, do you? (According to your comment, you do)

我发现了一个 MSDN 论坛上的链接建议直接访问 Scrollviewer 以进行滚动.对我来说,那里提供的解决方案看起来很像一个黑客,但你可以自己决定.

I have found a link on MSDN forums that suggest accessing the Scrollviewer directly in order to scroll. To me the solution presented there looks very much like a hack, but you can decide for yourself.

这是上面的链接:

VirtualizingStackPanel vsp =  
  (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember("_itemsHost",
   BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null, 
   _listView, null);

double scrollHeight = vsp.ScrollOwner.ScrollableHeight;

// itemIndex_ is index of the item which we want to show in the middle of the view
double offset = scrollHeight * itemIndex_ / _listView.Items.Count;

vsp.SetVerticalOffset(offset);

这篇关于将 WPF Listview 滚动到特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆