Reputation: 2581
The Width
of a ScrollViewer
remains "normal" if it is used like this:
<Grid>
<ScrollViewer>
<Rectangle Width="2500"/>
</ScrollViewer>
</Grid>
Saying "Normal" I've meant that the ScrollViewer
's Width
is going to be the same as the Grid
(1500 in my case) as I didn't mention their Width
myself. At least that's what i know.
But, if the above portion is taken inside a StackPanel like this:
<StackPanel Orientation="Horizontal">
<Grid>
<ScrollViewer>
<Rectangle Width="2500"/>
</ScrollViewer>
</Grid>
</StackPanel>
then the ScrollViewer
's Width
become 2500 as it's Content's Width
.
What's the reason?
Upvotes: 1
Views: 200
Reputation: 1580
The layout procedure in XAML has two phases Measure and Arrange.
During the Measure phase, usually, most panels will ask their children "What size do you want to be?" (this will effectively walk down the tree). And the parent of the children can decide what size it wants to be based on it's children. It returns this Size
in its MeasureOverride
method.
Once everything has been measured, it's time to actually Arrange and layout things on the screen. This is when the actual size of elements is determined. The system starts by telling each element "This is how much space you have." Each panel then, starting at the top, can then tell it's child where to be within its space and how much space it actually has to take up (done by calling Arrange
on each child in the ArrangeOverride
method of a parent custom panel).
You can see the full documentation for this here.
So in your two examples the outcome is different because of how Grids and StackPanels behave:
With the Grid as a root, in your top example, it takes up the available space and tells its children they have to fit inside it. So the ScrollViewer says it wants to be larger because of it's child rectangle, but in the end the Grid says you only have 1500 units of space because that's all it was given. So the ScrollViewer will show a scrollbar if you turn on HorizontalScrollBarVisibility
to let you pan to see the whole rectangle.
With the StackPanel as a root, it will expand itself to accommodate the size of its children. Therefore, when the ScrollViewer tells the Grid it wants to be this size for its contents, that gets passed up through the Grid to the StackPanel. When it comes time to Arrange, the StackPanel tells the Grid that it has all the space it requested, which is the extra space the Rectangle wanted. This extra space just gets clipped by the page/window in the end when its displayed.
This is why there's so many different layout panels available as they all behave differently during these two steps to arrange one or more content items for a desired effect. It's also why using StackPanels everywhere can be tricky as they're always greedy compared to other panels which will behave more 'predictably'.
Upvotes: 1