显示添加到 ItemsControl 的最新项目
我不敢相信在搜索谷歌和 SO 半个小时后我找不到解决方案。
我的 ViewModel 中有一个 ObservableCollection
,我的视图中的 ListBox
绑定到它:
<ListBox ItemsSource="{Binding Output}" IsSynchronizedWithCurrentItem="True" />
单击按钮时,一个新线程会执行一些操作,并且,使用 Observable,VM 监视从该异步操作返回的字符串,并将这些字符串添加到其 Output
ObservableCollection
中。添加字符串没有问题,但如何让视图始终显示最新项目(最近添加的项目)?
I can't believe that I couldn't find a solution to this after searching google and SO for a half-hour.
I've got an ObservableCollection<string>
in my ViewModel that a ListBox
in my View is bound to:
<ListBox ItemsSource="{Binding Output}" IsSynchronizedWithCurrentItem="True" />
When a button is clicked, a new thread does some stuff and, using an Observable, the VM monitors strings coming back from that async operation and adds the strings to its Output
ObservableCollection
. The strings are getting added with no problem, but how to I get the view to always show the latest item (the one most recently added)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的商品是否显示在列表中但位于更下方?如果是这种情况,您所需要做的就是告诉列表将该项目滚动到视图中。您可以通过订阅 ListBox.Items 属性的 CollectionChanged 来完成此操作。要做到这一点有点棘手,因为您必须强制转换它,但您可以使用如下代码来执行此操作:
然后在该事件中您可以添加如下代码:
另外,我刚刚找到了一种可以使用附加属性来执行此操作的方法,即很酷。在这里查看:
http://michlg.wordpress.com/ 2010/01/16/列表框自动滚动当前项目进入视图/
Does your item show up in the list but just farther down? If that is the case all you need to do is tell the list to scroll that item into view. You can do this by subscribing to the ColllectionChanged of the ListBox.Items property. To do this is a little tricky because you have to cast it but you can do so with code like this:
Then inside that event you can add code like this:
Also I just found a way you can do this with an attached property that is pretty cool. Check it out here:
http://michlg.wordpress.com/2010/01/16/listbox-automatically-scroll-currentitem-into-view/