I have a DataGrid:
<DataGrid ...></DataGrid>
Somewhere there in the default template, there’s a ScrollViewer. I want to add content inside it. Currently I am doing this:
<Grid>
<DataGrid Grid.Row="0">...</DataGrid>
<Canvas Width="128" VerticalAlignment="Stretch" HorizontalAlignment="Left" Grid.Row="0" Margin="0,25,0,0">
<Rectangle Width="32" Height="256" Canvas.Top="0" Canvas.Left="0" Stroke="Black" StrokeThickness="2" />
</Canvas>
</Grid>
Which looks like this:

That is, the canvas gets drawn inside the grid. This is all great, but the canvas does not scroll along with the data grid. Now I realize I probably need to alter the control template and put the canvas inside the scroll viewer:
<DataGrid>
<ControlTemplate>
<ScrollViewer>
<Grid>
<ContentPresenter Grid.Row="0" />
<Canvas Width="128" VerticalAlignment="Stretch" HorizontalAlignment="Left" Grid.Row="0" Margin="0,25,0,0">
<Rectangle Width="32" Height="256" Canvas.Top="0" Canvas.Left="0" Stroke="Black" StrokeThickness="2" />
</Canvas>
</Grid>
</ScrollViewer>
</ControlTemplate>
</DataGrid>
However, this is giving me the error:
A first chance exception of type ‘System.InvalidOperationException’
occurred in PresentationFramework.dllAdditional information: Items collection must be empty before using
ItemsSource.
How do I place the canvas inside the scroller to make it scroll along with the content?
DataGrid is an ItemsControl and the ContentProperty for an ItemsControl is the Items property. Here’s the decompiled source, notice the ContentProperty attribute:
This means that if you do something like this:
Then
<SomethingHere>– which is the content – is applied to theItemsproperty. If you subsequently bind to theItemsSourceproperty you will get the error you’re seeing – “Items collection must be empty before using ItemsSource.”If you had used
You wouldn’t get the error.
In any case it would be better to extract the DataGrid’s full ControlTemplate using Blend or VS11 and modify that, e.g.