StackPanel 中的 DataGrid 导致 OutOfMemoryException
我在 WPF 窗口中有网格,里面有一个 DataGrid 控件:
<Grid>
<DataGrid ItemsSource="{Binding AllAuthors}" />
</Grid>
AllAuthors
是一个 ObservableCollection
和 Author
是一个简单的类,只有几个字符串属性。该集合包含大约 40000 个隐藏代码对象。数据网格打开得非常快(1 秒后),并且数据网格中的导航流畅且快速。该应用程序的内存负载为 35 MB。
如果我用……替换上面的代码
<StackPanel>
<DataGrid ItemsSource="{Binding AllAuthors}" />
</StackPanel>
,应用程序会以 100% CPU 负载运行,并且当应用程序尝试显示 DataGrid 时,内存会持续增长到 1.5 GB。最后我收到一个 OutOfMemoryException
。
我是 WPF 初学者,现在想知道这里出了什么问题。 (我使用的是VS2010、.NET 4.0和WPF 4.0内置的DataGrid控件)
提前感谢您的帮助!
I have grid in a WPF window and a DataGrid control inside:
<Grid>
<DataGrid ItemsSource="{Binding AllAuthors}" />
</Grid>
AllAuthors
is an ObservableCollection<Author>
and Author
a simple class with only a few string properties. The collection is populated with around 40000 objects in code behind. The DataGrid opens quite quickly (after 1 sec) and navigation through the datagrid goes smooth and fast. The application has a memory load of 35 MB.
If I replace the code above by ...
<StackPanel>
<DataGrid ItemsSource="{Binding AllAuthors}" />
</StackPanel>
... the application runs with 100% CPU load and memory grows continuously up to 1,5 GB while the application is trying to display the DataGrid. Finally I receive an OutOfMemoryException
.
I'm WPF beginner and wondering now what's wrong here.
(I'm using VS2010, .NET 4.0 and the built-in DataGrid control of WPF 4.0)
Thank you for help in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要它在网格中,这就不是问题,因为实际上可能只生成了几个项目 - 当前实际上可见的项目。这称为 UI 虚拟化,并内置于 WPF 中的多个 ItemsControl 中。由于 DataGrid 相当小,因此实际生成的 Item 并不多。
但是,当您将其放入 StackPanel 中时,您可能会构建一个布局,其中 StackPanel 扩展到 DataGrid 的高度,而 DataGrid 则占用它认为需要的空间。我们需要查看完整的 xaml 来查看情况是否如此。不管怎样,如果是的话,现在实际上有相当多的项目“可见”(即所有项目)。而生成 40000 个项目显然不是一个好主意。
您是否比较过两个 DataGrid 的 ActualHeight 属性?
As long as it is in the grid, this is not a problem since probably only a few items are actually generated - the ones that are actually currently visible. This is called UI virtualization and is built into several ItemsControls in WPF. Since the DataGrid is rather small, there are not too much Items actually generated.
However when you put it in the StackPanel you might have build a layout where the StackPanel expands to the height of the DataGrid while the DataGrid takes as much space as it thinks it needs. We would need see the complete xaml to see if that is the case. Anyway, if it is, now there are actually quite a lot of items "visible" (i.e. all of them). And generating 40000 items is obviously not a good idea.
Have you compared the ActualHeight property of the two DataGrids?