bradygaster.com

fewer resources, less time, more features

Zooming with the Mouse Wheel in WPF

January 29 2008
Posted to:

Not exactly sure if one could refer to this as "real zooming" or whatever, but it's a nifty trick that I've been thinking about implementing for a few days and finally had the time to do so. With that said, let's get to it. The point of this post is to explain how to allow for users who would like to zoom in on (or increase the size of, to be specific) specific controls on a WPF window. The code to do this is surprisingly simple. In fact, I'd be interested to see any improvements on this method.

The XAML code for a sample window is below. Note that I've just added one simple Rectangle to the window's Grid and attached the MouseWheel event to my local OnMouseWheel event handler. I'll examine the code for the OnMouseWheel handler in a moment, but for now here's some really simple XAML.

    5       <Grid>

    6         <Rectangle MouseWheel="OnMouseWheel" Width="100" Height="100" Name="rectangle1">

    7             <Rectangle.Fill>

    8                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">

    9                     <GradientStop Color="ForestGreen" Offset=".1"/>

   10                     <GradientStop Color="Khaki" Offset=".6"/>

   11                 </LinearGradientBrush>

   12             </Rectangle.Fill>

   13         </Rectangle>

   14     </Grid>

Of course, here's the handler method. In it, I examine the sender parameter as a FrameworkElement, as that's the base class for the majority of the controls for which I'd like to provide zoomability. Sure, I made the word up. Quit being cynical and look at the code.

   27         private void OnMouseWheel(object sender, MouseWheelEventArgs e)

   28         {

   29             FrameworkElement source = sender as FrameworkElement;

   30             if (source == null) return;

   31             source.Width = rectangle1.Width + (e.Delta / 10);

   32             source.Height = rectangle1.Width + (e.Delta / 10);

   33         }

That's it. You can attach this event handler to the MouseWheel event of any control that inherits from FrameworkElement and provide zoomability for your users.

Happy coding! 

Comments Email Permalink Bookmark and Share kick it

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



FriendFeed