Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

WPF ScrollViewer Scrolls Controls

This WPF example uses the ScrollViewer control to provide a scrollable area for sub-controls.

ScrollViewer. A ScrollViewer scrolls other controls.

It is used as a container. We drag (or otherwise add) controls, nesting them inside the ScrollViewer. And then it automatically allows scrolling of the interior area.

Based on:

.NET 4.5

Example. Interface 5. To use a ScrollViewer please open the Toolbox and drag the control to your Window. The ScrollViewer is worthless with no internal controls. So try dragging some Button controls (or any control) to its interior area.

In this example, I added a StackPanel to the interior of the ScrollViewer. In a StackPanel, controls are "stacked" in one direction. Other controls, not just StackPanel work just as well within a ScrollViewer.


Here: I dragged three Button controls to the ScrollViewer. I then added margin to the Buttons to make them larger in area.

Result: In the final program, the buttons can be scrolled up and down with the scroll bar located on the right of the window.

Example markup: XAML

<Window x:Class="WpfApplication6.MainWindow"
	Title="MainWindow" Height="350" Width="525">
	<ScrollViewer HorizontalAlignment="Left" Height="299" Margin="10,10,0,0"
		      VerticalAlignment="Top" Width="497">
		<Button Content="Button 1" HorizontalAlignment="Left" Margin="50"
			VerticalAlignment="Top" Width="75"/>
		<Button Content="Button 2" HorizontalAlignment="Left" Margin="50"
			VerticalAlignment="Top" Width="75"/>
		<Button Content="Button 3" HorizontalAlignment="Left" Margin="50"
			VerticalAlignment="Top" Width="75"/>

Discussion. ScrollViewer is a layout control. It requires you to add controls to it before it is useful. Once you do this, though, you get a region that expands as much as needed. This can lead to more versatile interfaces.

And: You won't need to redesign your entire program just to add another button or TextBlock description.



Sometimes when designing programs, a "Preferences" dialog (Options) is a burden. At first, these windows have few controls. So you can just add Buttons to a Grid. This is straightforward and easy.

But: As time passes, the program becomes more complex. At that point, a ScrollViewer might be helpful. It will scroll as far as needed.

Summary. WPF is full of useful controls. Many of them are only helpful in narrow contexts, though. A ScrollViewer is not needed in many programs. In Options Windows, or other complex dialogs, it has its place.