views:

121

answers:

2

Hi I was wondering if there is any way to force a scrollbar to scroll a canvas. I placed canvas in scrollview and I overrode the measureoverride method. Scrollbars show when I reach the ends of visible parts of the canvas. However I would like the canvas to scroll because now, despite the fact that scrollbars show, the canvas does not follow item. I hope you understand me, sorry for my bad English :)

A: 

Hi quasimodo,

Let me try,

1) You have a hosted a canvas inside a scroll viewer.
2) When the canvas size increases, the scroll viewer is appearing. [Since, you have set the horizontal or vertical scrollbar visibility to auto]
3) What you want is, When you reach the end of the canvas [Size of canvas gets increases, so scroll bars of scroll viewer will appear.] you want the scroll bar of the scroll viewer to scroll automatically to show the extra space.

If, the above question is right. Here goes, the answer.

You have to do a calculation based on the ActualWidth or ActualHeight of the canvas and set the value to the ScrollToHorizontalOffset or ScrollToVerticalOffset property accordingly.

Avatar
A: 

Below sample will show a red circle in a blue canvas which will have vertical and horizontal scrollbars if it don't fit in the window.

<Window x:Class="WpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">

    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <Canvas Width="500" Height="500" Background="Yellow">
            <Ellipse 
                Stroke="Red" StrokeThickness="10" 
                Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}}}" 
                Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}}}" />
        </Canvas>
    </ScrollViewer>

</Window>
Wallstreet Programmer