如何:替换 DocumentViewer 的样式

更新:2007 年 11 月

此示例演示如何替换 DocumentViewer 控件的默认样式。

示例

下面的可扩展应用程序标记语言 (XAML) 代码定义一个窗口,其中包含一个 DocumentViewer 控件及其随附的样式。此示例样式使用 ControlTemplate 来替换默认的 DocumentViewer 样式。在本例中,示例样式只定义一个厚度为十个像素的 Border,并向边框DocumentViewer 用来显示内容的内部 ScrollViewer 的背景应用渐变颜色。

<Window x:Class="SDKSample.Window1"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="DocumentViewer_ExtendStyle">
  <Window.Resources>
    <Style 
      x:Key="MyDVStyleReplace"
      TargetType="{x:Type DocumentViewer}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type DocumentViewer}">
            <Grid>
              <Border BorderThickness="10">
                <Border.BorderBrush>
                  <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                    <LinearGradientBrush.GradientStops>
                      <GradientStop Color="Yellow" Offset="0" />
                      <GradientStop Color="Red" Offset="0.25" />
                      <GradientStop Color="Blue" Offset="0.75" />
                      <GradientStop Color="LimeGreen" Offset="1" />
                    </LinearGradientBrush.GradientStops>
                  </LinearGradientBrush>
                </Border.BorderBrush>
                <ScrollViewer Name="PART_ContentHost">
                  <ScrollViewer.Background>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                      <LinearGradientBrush.GradientStops>
                        <GradientStop Color="Yellow" Offset="0" />
                        <GradientStop Color="Green" Offset="1" />
                      </LinearGradientBrush.GradientStops>
                    </LinearGradientBrush>
                  </ScrollViewer.Background>
                </ScrollViewer>
              </Border>
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>
  <Grid>
    <DocumentViewer  Style="{StaticResource MyDVStyleReplace}" Name="MyDocumentViewer"/>
  </Grid>
</Window>

任务备注

  • 由于此示例中所演示的样式会替换 DocumentViewer 的默认样式,而不是扩展它,因此 DocumentViewer 工具栏、上下文菜单和其他 用户界面 (UI) 元素(由默认的 DocumentViewer 样式来定义)将不显示。

  • 在替换 DocumentViewer 控件的样式时,控件模板中必须包括一个其 Name 为“PART_ContentHost”的 ScrollViewer

  • 样式是通过将样式键 (x:Key) 与元素的 Style 属性所引用的值相匹配来应用的。在上面的示例中,样式键是“MyDVStyleReplace”。该键本身是必须在当前范围内保持唯一的任意字符串值。

  • 定义为本地资源的样式必须使用上例中所示的 StaticResource 语法,以静态资源形式引用。

  • 样式和 ControlTempate 使用 TargetType 来指示样式仅适用于 DocumentViewer 控件。如果样式或控件模板的目标类型与样式所应用到的元素不匹配,则将引发 InvalidOperationException 异常。

请参见

任务

如何:扩展 DocumentViewer 的样式

参考

DocumentViewer

StaticResourceExtension