Scrollviewer not working on a grid

北城以北 提交于 2019-12-04 03:58:47

This is a common mistake for beginners and you should not feel bad about it. The thing to remember about the scroll viewer is that it MUST have a height and width. Sometimes you set the height and width. Sometimes you let the height and width be set by the size of the container. Right?

Look at this:

<ScrollViewer>
    <Grid Height="1000" />
</ScrollViewer>

In that sample, the scroll viewer would act like it is not even there. Why? Because it does not have a height and width. It would just be the same size as its content in that case. That's basically what you are seeing.

Look at this:

<ScrollViewer Height="100">
    <Grid Height="1000" />
</ScrollViewer>

This would scroll just fine vertically but it would never scroll horizontally. Can you see why? It's because there is not width. Sometimes this is the perfect scenario. But it's another thing that can catch a developer off guard.

Look at this:

<StackPanel>
    <ScrollViewer>
        <Grid Height="1000" />
    </ScrollViewer>
<StackPanel>

This is another scenario that catches a lot of developers. Why? Because the height of a stack panel is infinite. Since the height and the width are basically inherited by the container, the scroll viewer never has a reason to scroll as it is already allows to grow to infinite size.

Look at this:

<Grid>
    <ScrollViewer>
        <Grid Height="1000" />
    </ScrollViewer>
<Grid>

Perfect. Now the scroll viewer will scroll just like you want it to because the height and the width of the scroll viewer are inherited by the height and the width of its container, the grid. And because a grid constraints itself to the size of the window, you are in great shape.

You can spoil the behavior of the grid, of course, by putting it in a stack panel! Don't do that unless you know what you are doing and causing. If you are new to XAML you might enjoy this free course on Microsoft Virtual Academy.

I hope this helps.

Best of luck!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!