#886 – Wrapping a Canvas in a ScrollViewer

Because the ScrollViewer control is a ContentControl, it can contain any single element.  It most often contains a single Panel, which in turn contains child elements.

Below is an example of a ScrollViewer that contains a Canvas, which in turn contains several different elements.  When the containing window is sized to be smaller than the Canvas element, the scrollbars automatically appear.

    <ScrollViewer HorizontalScrollBarVisibility="Auto"
                  VerticalScrollBarVisibility="Auto">
        <Canvas Width="340" Height="330">
            <Image Canvas.Left="15" Canvas.Top="5"
                   Source="Augustus.jpg" Height="100" Margin="10"/>
            <Label Canvas.Left="0" Canvas.Top="120"
                Grid.Column="1" Content="Augustus - 63BC - 14AD" />

            <Image Canvas.Top="180" Canvas.Left="200"
                   Grid.Column="2" Source="Tiberius.jpg" Height="100" Margin="10"/>
            <Label Canvas.Top="295" Canvas.Left="180"
                   Grid.Column="3" Content="Tiberius - 42BC - 37AD"/>

            <Line Canvas.Left="140" Canvas.Top="140" X2="65" Y2="50"
                  Stroke="RoyalBlue"/>
        </Canvas>
    </ScrollViewer>

886-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

4 Responses to #886 – Wrapping a Canvas in a ScrollViewer

  1. Pingback: Dew Drop – August 16, 2013 (#1,605) | Alvin Ashcraft's Morning Dew

  2. Saleh Rezaei says:

    Hi, I have a canvas that many children are added to it dynamically, i want to zoom and have the children zoomed too. I’ve used rendertransform which works fine, but it doesn’t trigger the scrollviewer. I tried layouttransform, but it doesn’t zoom.
    Please help me
    thanks

    • Sean says:

      It’s hard to tell exactly what you’re doing without seeing code. Perhaps you need to also change the size of the canvas when you do the transform? I would also try using a scale transform.

  3. Kevin Walsh says:

    Canvas always reports its size as 0,0 to it’s parent container. Consider using MeasureOverride to iterate over the Canvas children and calculate the extents of the Canvas and returning the true width to the parent. That should get the scrollbars going. There are many samples of this on the interwebs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: