Geslot Geslot - 3 months ago 21
C# Question

ScrollViewer does not work inside Canvas

I am trying to use

ScrollViewer
inside
Canvas
, but scrolling does not work.

<Page
x:Class="ScrollViewerInCanvas.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ScrollViewerInCanvas"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Canvas>
<ScrollViewer>
<StackPanel Orientation="Vertical" Width="400">
<TextBlock Text="Just a huge text that will not fit into a single frame"
FontSize="100" TextWrapping="WrapWholeWords" />
</StackPanel>
</ScrollViewer>
</Canvas>
</Grid>
</Page>


But if I switch
Canvas
with
Grid
everything works. Is there any way to get
ScrollViewer
work inside
Canvas
?

Answer

Based on the code you included in your post, it does not appear you gave the ScrollViewer any reason to need to scroll. A Canvas element doesn't constrain its children in any way. So in the Canvas, the ScrollViewer can be as large as it wants, and so it's going to be big enough to contain its children without scrolling. In a Grid, it would be stretched to fit its cell, so if the cell is smaller than the children, it will allow scrolling. Give it a reason to scroll, and it will.

For example, you could make the ScrollViewer always be the same dimensions as its Canvas parent:

<Page
    x:Class="ScrollViewerInCanvas.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScrollViewerInCanvas"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

  <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Canvas x:Name="canvas1">
      <ScrollViewer Width="{Binding ActualWidth, ElementName=canvas1}"
                    Height="{Binding ActualHeight, ElementName=canvas1}">
        <StackPanel Orientation="Vertical" Width="400">
          <TextBlock Text="Just a huge text that will not fit into a single frame"
                     FontSize="100" TextWrapping="WrapWholeWords" />
        </StackPanel>
      </ScrollViewer>
    </Canvas>
  </Grid>
</Page>

Anything that would constrain the size of the ScrollViewer to something smaller than the size of its content would cause the scroll bars to become visible and usable.