如何:替换 RichTextBox 的默认内容宿主
更新:2007 年 11 月
本示例演示如何使用 Windows Presentation Foundation (WPF) 样式来替换 RichTextBox 的默认内容宿主。
内容宿主是呈现 RichTextBox 的内容的元素。 RichTextBox 的默认控件模板将 ScrollViewer 指定为内容宿主。
如果由 ScrollViewer 提供的滚动功能是不想要或不需要的,则可以将轻量 AdornerDecorator 元素指定为 RichTextBox 的内容宿主。 内容宿主仅支持 ScrollViewer 和 AdornerDecorator 元素。
有关对此示例进行演示的有效示例,请参见替换 RichTextBox 的默认内容宿主示例。
示例
RichTextBox 的 ControlTemplate 必须包含且仅包含一个标记为内容宿主元素的元素。若要将某个元素标记为内容宿主,应为它指定特殊名称 PART_ContentHost。内容宿主元素必须为 ScrollViewer 或 AdornerDecorator。内容宿主元素可能不会承载任何子元素。
下面的可扩展应用程序标记语言 (XAML) 示例定义一个重写 RichTextBox 的默认控件模板的样式。 此样式与从 TextBoxBase 继承的元素兼容。 在本示例中,AdornerDecorator 指定为内容宿主。
<Window.Resources>
<Style x:Key="TextBoxNoScrollViewer" TargetType="{x:Type TextBoxBase}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border
CornerRadius="2"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
>
<!--
The control template for a TextBox or RichTextBox must
include an element tagged as the content host. An element is
tagged as the content host element when it has the special name
PART_ContentHost. The content host element must be a ScrollViewer,
or an element that derives from Decorator.
-->
<AdornerDecorator
x:Name="PART_ContentHost"
Focusable="False"
/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
下面的 XAML 示例通过结合使用 Style 属性和对样式的 x:Key 属性的静态资源引用,来定义一个采用以前声明的样式的 RichTextBox。
<RichTextBox
Grid.Column="0"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
Style="{StaticResource TextBoxNoScrollViewer}"
>
<FlowDocument>
<Paragraph>
RichTextBox styled not to use a ScrollViewer as the content host.
</Paragraph>
</FlowDocument>
</RichTextBox>