更新:2007 年 11 月
本範例顯示如何取代 DocumentViewer 控制項的預設樣式。
範例
下列可延伸標記語言 (XAML) 程式碼所定義的視窗包含 DocumentViewer 控制項和伴隨的樣式。範例樣式用 ControlTemplate 取代預設的 DocumentViewer 樣式。在這個案例中,範例樣式僅定義十個像素粗的 Border,並將漸層色彩套用至 Border 以及 DocumentViewer 用於顯示內容之內部 ScrollViewer 的背景 (Background)。
<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 例外狀況。