views:

18

answers:

1

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!

+1  A: 

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?

bitbonk
Thanks for reply! I've just compared ActualHeight for the Grid and StackPanel layout (for only 500 items) and you're right: If the DataGrid is in a Grid the height is only 440, if it's in a StackPanel it grows to over 8800. I've also set `EnableRowVirtualization=False` on the DataGrid for a test and in that case I have the same memory and performance issue with the Grid layout. What I don't understand is why I have a memory load of over 1,5 GB. The `Author` objects have a size of less than 200 Byte, so with 40000 objects where do 1,5 GB come from?
Slauma
This comes from all the WPF Visuals that are generated for each `Author` item based on the ItemTemplate.
bitbonk
OK, I see. I've specified a `Height` of 400 now on the DataGrid and now it is also working with the StackPanel. So, if I conclude correctly, a `Grid` restricts the controls inside of the grid to the visible window area while a `StackPanel` can grow into the invisible area of the window according to the needs of the different controls inside. Is that right? Anyway, your answer helped a lot. Thanks again!
Slauma
It kind of depends on what the parent of the Grid/StackPanel is.
bitbonk