Search code examples
wpfdatagridwpfdatagridstackpanel

DataGrid in a StackPanel leads to OutOfMemoryException


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!


Solution

  • 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?