Working With A ScrollViewer Control In A WPF Application

The ScrollViewer is an object that represents a scrollable area that contains other visible controls, it could be found within the System.Windows.Controls. At the contrast of a ScrollBar object, the ScrollViewer is a WPF new feature. So let's discover its principal characteristics through this article.

Imagine that you host an image in your application in such way that its dimensions are bigger than the window. You can make use of a ScrollViewer to enable see the entire image without having the obligation to change the dimension of the given window. Try to host a big image within a given window. Say that the image height and width are both 1000 pixels.

  1. <Window x:Class="myWpfApplication.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" Loaded="Window_Loaded">  
  2.     <Image Source="C:\myWpfApplication\myWpfApplication\image.BMP" Width="1000" Height="1000">  
  3. </Image>  

The result will be:

Working With A ScrollViewer Control In A WPF Application
Figure 1

And even you expand the window. You couldn't get the entire image at the screen level. To prevent this problem you may use the ScrollViewer object as follow:

Replace the above XAML code by this one.

  1. <Window x:Class="myWpfApplication.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" Loaded="Window_Loaded">  
  2.     <Grid>  
  3.         <ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">  
  4.             <Image Source="C:\myWpfApplication\myWpfApplication\image.BMP" Width="1000" Height="1000"></Image>  
  5.         </ScrollViewer>  
  6.     </Grid>  
  7. </Window>  

And the result will be

Working With A ScrollViewer Control In A WPF Application
Figure 2

Then it is possible to scroll the image.That's it

Good Dotneting!!!


Recommended Free Ebook
Similar Articles