This documentation is archived and is not being maintained.

How to: Create a ScrollViewer

This example shows how to create and use a ScrollViewer element in Extensible Application Markup Language (XAML).

The following example creates a window that contains some text and a rectangle. The scroll bars appear only when they are needed. When you resize the window, the scroll bars appear and disappear.

For the complete sample, see Scroll Viewer Sample.


// Create the application's main window
mainWindow = new Window ();
mainWindow.Title = "ScrollViewer Sample";

// Define a ScrollViewer
myScrollViewer = new ScrollViewer();
myScrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;

// Add Layout control
myStackPanel = new StackPanel();
myStackPanel.HorizontalAlignment = HorizontalAlignment.Left;
myStackPanel.VerticalAlignment = VerticalAlignment.Top;

TextBlock myTextBlock = new TextBlock();
myTextBlock.TextWrapping = TextWrapping.Wrap;
myTextBlock.Margin = new Thickness(0, 0, 0, 20);
myTextBlock.Text = "Scrolling is enabled when it is necessary. Resize the Window, making it larger and smaller.";

Rectangle myRectangle = new Rectangle();
myRectangle.Fill = Brushes.Red;
myRectangle.Width = 500;
myRectangle.Height = 500;

// Add child elements to the parent StackPanel
// Add the StackPanel as the lone Child of the Border
myScrollViewer.Content = myStackPanel;

// Add the Border as the Content of the Parent Window Object
mainWindow.Content = myScrollViewer;
mainWindow.Show ();

<Page xmlns=""
      WindowTitle="ScrollViewer Sample">
  <ScrollViewer HorizontalScrollBarVisibility="Auto">
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
      <TextBlock TextWrapping="Wrap" Margin="0,0,0,20">Scrolling is enabled when it is necessary. 
      Resize the window, making it larger and smaller.</TextBlock>
      <Rectangle Fill="Red" Width="500" Height="500"></Rectangle>

See Also