自动滚动到我最后添加的ListView项目导致InvalidoperationException

时间:2015-11-24 11:30:38

标签: wpf listview

我有这个系列:

public ObservableCollection<MyData> files { get; set; }

潜入CollectionChanged事件:

files.CollectionChanged += files_CollectionChanged;

当新项目添加到我的ListView

    private void files_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                listView.ItemsSource = files;
                listView.SelectedIndex = listView.Items.Count - 1;
                listView.ScrollIntoView(listView.SelectedItem);
            }
        }));
    }

我这样做的原因是我希望看到添加的文件并自动滚动最后添加的项目。

结果是InvalidoperationException

  

ItemsControl与其项目源不一致。看到内心   有关更多信息的例外。

更新

内部异常:

{&#34;开发人员的信息(使用Text Visualizer读取此内容):\ r \ n此异常被抛出,因为用于控制的生成器&System; Windows.Windows.Controls.ListView Items.Count:6&#39 ;名字&#39; listView&#39;收到了与Items集合的当前状态不一致的CollectionChanged事件序列。检测到以下差异:\ r \ n \ n \ n累计计数2与实际计数6不同。[累计计数为(最后一次重置计数+ #Adds - 自上次重置后#Removes)。] \ r \ n \ r \ n一个或更多以下来源可能引发了错误事件:\ r \ n System.Windows.Controls.ItemContainerGenerator \ r \ n System.Windows.Controls.ItemCollection \ r \ n System.Windows.Data.ListCollectionView \ r \ n系统.Collections.ObjectModel.ObservableCollection`1 [app name,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = null]] \ r \ n(已加星标的来源被认为更有可能是问题的原因。)\ r \ n \ n \ r \ n最常见的原因是(a)在不引发相应事件的情况下更改集合或其计数,以及(b)使用不正确的索引或项目参数引发事件。\ r \ n \ r \ n例外&# 39; s堆栈跟踪描述了如何检测到不一致性,而不是它们是如何发生的。要获得更及时的异常,请设置附加属性&#39; PresentationTraceSources.TraceLevel&#39;在发电机上重视&#39;高&#39;并重新运行该方案。一种方法是运行类似于以下命令:\ n System.Diagnostics.PresentationTraceSources.SetTraceLevel(myItemsControl.ItemContainerGenerator,System.Diagnostics.PresentationTraceLevel.High)\ r \ n从立即窗口。这会导致检测逻辑在每个CollectionChanged事件之后运行,因此会降低应用程序的速度。\ r \ n&#34;}

发生异常是因为这一行(当删除这一切时都很好):

listView.ScrollIntoView(listView.SelectedItem);

1 个答案:

答案 0 :(得分:0)

尝试将滚动分离为设置当前所选项目的视图。

连接ListView SelectionChanged =“OnSelectionChanged”并按如下方式实现:

private void OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
    Selector selector = sender as Selector;
    ListView listView = selector as ListView;
    if ( listView != null && selector.SelectedItem != null )
    {
        listView.ScrollIntoView( selector.SelectedItem );
    }
}

对于ObservableCollection.CollectionChanged:

private void OnCollectionChanged( object sender,
        NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs )
{
    if ( notifyCollectionChangedEventArgs.NewItems != null )
    {
        var newItem = notifyCollectionChangedEventArgs.NewItems.Cast<MyData>().LastOrDefault();
        if ( newItem != null )
        {
            listView.SelectedItem = newItem;
        }
    }
}

我不确定为什么每次收集更改时都要更改listView.ItemsSource。看起来你通常只​​是在新手或设置ObservableCollection时这样做。

相关问题