wpfcanvasscrollbars

How to draw scrollbars on WPF Canvas


I am trying to create a canvas with scroll bars. Can anyone help me give some ideas on how to do this? I have already tried using grid of 1 row and 1 column but due to certain constraints I want to use canvas.

Thanks in advance!


Solution

  • You could put the canvas inside of a scrollviewer. I tried this quick test and it allowed me to scroll through the contents of the canvas.

    <ScrollViewer Height="100" Width="200">
        <Canvas Height="400" Width="400">
                //Content here
        </Canvas>
    </ScrollViewer>
    

    edit: Here is an example where the scroll-bars show up only when needed, and it changes dynamically as the canvas size changes.

        <Button Content="Change Canvas Size" Click="ChangeCanvasSize_Click"/>
    <ScrollViewer Height="100" Width="200" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
        <Canvas x:Name="TestCanvas">
                <TextBlock Text="Test Test"/>
        </Canvas>
     </ScrollViewer>
    

    Changing canvas size with button click:

        private void ChangeCanvasSize_Click(object sender, RoutedEventArgs e)
        {
            TestCanvas.Width = 600;
            TestCanvas.Height = 600;
        }
    

    In this example, I start out with no scroll-bars and when I click the button to expand the canvas, scroll-bars appear.