1

I am trying to load an image within a canvas such that, if the size of image overflows the canvas, the scroll bars should get activated (MS Paint style)

<Window>
   <ScrollViewer>
        <Canvas  ScrollViewer.HorizontalScrollBarVisibility="Visible" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible">
            <Image Source="SampleImage.jpg" />
        </Canvas>
   </ScrollViewer>
 </Window>
  • Now as Canvas is stretched to Window's size, scroll-bars won't appear as Canvas is not actually overflowing out of the Window.
  • Secondly, as the Image is much bigger than the Canvas, it is getting clipped at the bounds of Canvas, so ScrollViewer doesn't think that its content: Canvas is actually overflowing.

It happens a lot of time with StackPanels too, that even though the bound data has tens of rows, but still the scrollbars don't get activated. Sometimes scrollviewers appear as mystery to me.

So, what should be the basic logic kept in mind when using ScrollViewer control.

Thank you.

Edit: Just edited the question title, so that whosoever has problem with canvas can get this question easily in search.

Marshal
  • 6,551
  • 13
  • 55
  • 91
  • Remove the canvas and it should works – Nicolas Repiquet May 28 '15 at 11:18
  • Yes, but why not with canvas. What if the image is not only control of the window, you may have menus, toolbar, statusbar etc. and hence it should have another container than a `Window`. – Marshal May 28 '15 at 11:22
  • 1
    see my answer, why not with canvas. Just replace Canvas with Grid if there's more elements. Use Canvas only when you dont care about its size. For scrolling purposes you need to know canvas size. There's no mystery in ScrollViewer :) – Liero May 28 '15 at 11:40

2 Answers2

6

From MSDN: Canvas is the only panel element that has no inherent layout characteristics. A Canvas has default Height and Width properties of zero, unless it is the child of an element that automatically sizes its child elements. Child elements of a Canvas are never resized, they are just positioned at their designated coordinates. This provides flexibility for situations in which inherent sizing constraints or alignment are not needed or wanted. For cases in which you want child content to be automatically resized and aligned, it is usually best to use a Grid element.

Hovever, you can set Canvas Height and Width explicitely:

<ScrollViewer Height="100" Width="200">
    <Canvas Height="400" Width="400">
            //Content here
    </Canvas>
</ScrollViewer>
Liero
  • 25,216
  • 29
  • 151
  • 297
  • 1
    Yes I just saw this answer here: [WPF: How to make canvas auto-resize?](http://stackoverflow.com/questions/855334/wpf-how-to-make-canvas-auto-resize/863108#863108). – Marshal May 28 '15 at 11:43