十二. ScrollViewer
通常用户界面中的内容比计算机屏幕的显示区域大,大出的部分就会破坏原有的布局。利用 ScrollViewer 控件可以方便地使应用程序中的内容具备滚动功能。这样大出的部分就可以正常显示出来了。常用属性、事件和继承关系见下面类图:

要实现的效果如下图(用XAML和C#实现同一效果):

XAML代码实现:
<Window
x:Class="WPFLayoutDemo.ScrollViewerDEMO"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ScrollViewerDEMO" Height="300" Width="300">
<Grid>
<ScrollViewer>
<Rectangle Width="500" Height="500" Fill="Gray">
</Rectangle>
</ScrollViewer>
</Grid>
</Window>
x:Class="WPFLayoutDemo.ScrollViewerDEMO"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ScrollViewerDEMO" Height="300" Width="300">
<Grid>
<ScrollViewer>
<Rectangle Width="500" Height="500" Fill="Gray">
</Rectangle>
</ScrollViewer>
</Grid>
</Window>
C#代码实现:
namespace WPFLayoutDemo
{
public partial class ScrollViewerDEMOCodeBehind : Window
{
public ScrollViewerDEMOCodeBehind()
{
InitializeComponent();
ScrollViewer myScrollViewer = new ScrollViewer();
myScrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
Rectangle myRectangle = new Rectangle();
myRectangle.Fill = Brushes.Gray;
myRectangle.Width = 500;
myRectangle.Height = 500;
myScrollViewer.Content = myRectangle;
this.Content = myScrollViewer;
}
}
}
{
public partial class ScrollViewerDEMOCodeBehind : Window
{
public ScrollViewerDEMOCodeBehind()
{
InitializeComponent();
ScrollViewer myScrollViewer = new ScrollViewer();
myScrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
Rectangle myRectangle = new Rectangle();
myRectangle.Fill = Brushes.Gray;
myRectangle.Width = 500;
myRectangle.Height = 500;
myScrollViewer.Content = myRectangle;
this.Content = myScrollViewer;
}
}
}
十三.布局综合应用
前面通过十多个小节讲了一些常用Panel的基本用法,那我们这里就简单做一个综合的小例子,通过这个例子,旨在巩固前面的内容,也可以当做一个举一反三的过程。要实现的效果如下图:
