【发布时间】:2010-10-22 05:13:26
【问题描述】:
我使用ListView 来显示我的应用程序中出现的错误列表。它的行为和外观与 Visual Studio 中的错误列表完全相同。我想在选择最后一个错误项时添加自动滚动(例如,当您将插入符号放在末尾时,Visual Studio 的日志窗口如何自动滚动)。
错误列表在ObservableCollection 中,像这样传递给ListView.ItemsSource:
public ObservableCollection<ErrorListItem> Items;
...
MyListView.ItemsSource = _Items;
我尝试在_Items_CollectionChanged 事件处理程序中执行自动滚动,但因为这是ItemsSource 上的事件,而不是实际ListViewItems 上的事件,所以很难确定是否选择了最后一项,选择新行等。这特别困难,因为似乎ListViewItems 不是立即创建的。我设法通过延迟设置最后一个项目的调用使其自动滚动,如下所示:
void _Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// determine the last item to select from 'e'
...
_ItemPendingToBeScrolled = newItemToSelect;
ListView.SelectedItem = newItemToSelect;
Dispatcher.BeginInvoke(DispatcherPriority.Background,
(ThreadStart)delegate
{
if (_ItemPendingToBeScrolled != null)
{
ListView.ScrollIntoView(_ItemPendingToBeScrolled);
ItemPendingToBeScrolled = null;
}
})
}
但这显然不是正确的做法。此外,如果列表被过滤,我希望事情继续工作(不检查我的源中的最后一项,但检查ListView 中的最后一个ListViewItem)。
当ListViewItem 在添加到绑定集合后添加到ListView 时,有没有办法监听事件?这将是为了正确进行自动滚动而捕获的理想事件。或者我可以使用其他技术吗?
【问题讨论】:
标签: wpf data-binding listview listviewitem