WPF ContentControl width grows but doesn't shrink when wrapped in a ScrollViewer
It seems to me that this is just another case of the dreaded StackPanel
layout problem. This problem comes up again and again and I confess that I had the very same problem when I started learning WPF. The StackPanel
does not take the available size of its parent into consideration whereas other Panel
s such as a DockPanel
or a Grid
(yes, that's actually a Panel
too) do.
It's explained in the How to: Choose Between StackPanel and DockPanel page on MSDN:
Although you can use either DockPanel or StackPanel to stack child elements, the two controls do not always produce the same results. For example, the order that you place child elements can affect the size of child elements in a DockPanel but not in a StackPanel. This different behavior occurs because StackPanel measures in the direction of stacking at Double.PositiveInfinity; however, DockPanel measures only the available size.
The StackPanel
should only really be used to align a number of items, such as Button
s or other controls in a straight line where available space is not a concern. So anyway, the solution should be simple... just remove the StackPanel
from the ScrollViewer
. It doesn't appear to serve any purpose there anyway.
UPDATE >>>
After looking again, it seems as though you're saying that the problem is inside the DataTemplate
, right? You might be able to fix that by setting the ItemsControl.HorizontalContentAlignment
property to Stretch
. That would ensure that each item remains within the boundary of the ItemsControl
.
I'd also remove your Binding
on the Grid.Width
as you don't need it... a child Grid
will take up the full space of a parent Grid
by default. If these ideas don't work, just simplify your problem. Seriously, if you follow the advise in the linked page from the Help Center that I gave you in the comments, then you'll either fix the problem, or be able to come back here and provide a complete, but concise example that we could test.
I've found the behavior I was looking for by using a UniformGrid
as the ItemsPanel
, with its rows bound to the count of the ItemsSource
model:
<ScrollViewer> <ItemsControl ItemsSource="{Binding MyCollection}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Rows="{Binding MyCollection.Count}" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> ... </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl></ScrollViewer>
As @Sheridan pointed out above, it seems the StackPanel
is causing trouble. Also, credit to https://stackoverflow.com/a/23375262/385273 for pointing out the UniformGrid
option.