MousePanning in WPF

Andrew Smith / Friday, April 04, 2008

Many applications such as Microsoft Office and web browsers provide the ability to scroll by pressing down the middle mouse button and dragging in the direction that you want to scroll. This feature is often referred to as mouse panning. When you press down the middle mouse button on a scrollable area, an indicator is displayed. This indicator usually has arrows that let you know whether you can scroll vertically and/or horizontally. You can then drag the mouse in a direction to cause the window to scroll.

We had incorporated this functionality into our UIElement framework in Windows Forms but any element that wanted to utilize it had to opt into the feature, override certain members, and process the panning notifications since scrolling functionality is implemented by each control. In WPF, elements that want to allow for scrolling normally do so by using a ScrollViewer. The MousePanningDecorator class takes advantage of this fact to provide mouse panning functionality to any ScrollViewer nested within it. You just need to create an instance of this element within your Window/Page and any ScrollViewer within it will receive mouse panning support.

MousePanningDecorator

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:sys="clr-namespace:System;assembly=mscorlib" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:igWindows="http://infragistics.com/Windows"
>
    <Grid>
        <igWindows:MousePanningDecorator>
            <ScrollViewer HorizontalScrollBarVisibility="Auto">
                <Image Stretch="None" 
                  Source="http://veimages.gsfc.nasa.gov/2433/land_shallow_topo_2048.jpg" />
            </ScrollViewer>
        </igWindows:MousePanningDecorator>
    </Grid>
</Page>

If you want to restyle the indicators, the class exposes several ResourceKey fields that can be used to provide custom ImageSources for the indicators.