加载所有项目并在ListView中显示后会触发哪个事件?

时间:2015-01-01 10:16:24

标签: c# .net wpf listview events

在WPF ListView中加载并显示所有项目后会触发哪个事件? 我尝试优化在ListView中显示大量项目。 ListView使用以下代码填充项目:

List<Artist> selectedArtistsList;
//Code to fill selectedArtistsList with about 6,000 items not shown here
CollectionViewSource selection1ViewSource = ((CollectionViewSource)(this.FindResource("selection1Source")));
Stopwatch stopWatch1 = new Stopwatch();
stopWatch1.Start();
selection1ViewSource.Source = selectedArtistsList;
stopWatch1.Stop();
Debug.Print("Time used: {0}ms", stopWatch1.ElapsedMilliseconds.ToString());

当我运行此代码时,我看到&#34;时间使用了119毫秒&#34;或类似的东西。但是在我看到屏幕上的ListView中的Items之前,它需要大约3秒钟。 是否有一个事件在ListView加载项目后触发? 我有兴趣测量ListView何时为用户做好准备。

1 个答案:

答案 0 :(得分:3)

感谢您的评论。我找到了解决方案。 在Nick Baker的评论之后,我用Google搜索了Dispatcher.Invoke。阅读和测试后,我找到了这个页面

WPF:窗口渲染完成后运行代码 http://geekswithblogs.net/ilich/archive/2012/10/16/running-code-when-windows-rendering-is-completed.aspx

然后我将代码更改为以下内容(不是完整代码,只是相关部分):

private void Work(){
    List<Artist> selectedArtistsList;
    //Code to fill selectedArtistsList with about 6,000 items not shown here
    CollectionViewSource selection1ViewSource = ((CollectionViewSource)(this.FindResource("selection1Source")));
    stopWatch1.Reset();
    stopWatch1.Start();
    selection1ViewSource.Source = selectedArtistsList;
    Debug.Print("After setting Source: {0}ms", stopWatch1.ElapsedMilliseconds.ToString());

    //New:
    Dispatcher.BeginInvoke(new Action(RenderingDone), System.Windows.Threading.DispatcherPriority.ContextIdle, null);
}

//New
Stopwatch stopWatch1 = new Stopwatch();
private void RenderingDone() {
    Debug.Print("After rendering is done: {0}ms", stopWatch1.ElapsedMilliseconds.ToString());
}

运行后我看到: 设置源:124ms后 渲染完成后:2273ms

渲染完成后显示最后一行,并显示正确的时间。这正是我想要的。

相关问题