Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This example shows how to use Windows Presentation Foundation (WPF) styles to replace the default content host for a TextBox.
The content host is the element that renders the contents of the TextBox. The default control template for a TextBox specifies a ScrollViewer as the content host. For an example of the default control template for a TextBox, see TextBox ControlTemplate Example.
In cases where the scrolling features provided by a ScrollViewer are unwanted or unneeded, a lighter-weight AdornerDecorator element may be specified as the content host for a TextBox.
For a working sample that demonstrates this example, see Replace the Default Content Host for a TextBox Sample.
Example
The ControlTemplate for a TextBox must contain exactly one element that is tagged as the content host element. To tag an element as the content host, assign it the special name PART_ContentHost. The content host element must be either a ScrollViewer or an AdornerDecorator. The content host element may not host any child elements.
The following Extensible Application Markup Language (XAML) example defines a style that overrides the default control template for a TextBox. This style is compatible with elements that descend from TextBoxBase. In the example, an AdornerDecorator is specified as the content host.
<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>
The following XAML example defines a TextBox that makes use of the previously declared style by using the Style attribute coupled with a static resource reference to the style's x:Key Attribute.
<TextBox
Grid.Column="0"
AcceptsReturn="True"
AcceptsTab="True"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
Style="{StaticResource TextBoxNoScrollViewer}"
>
TextBox styled not to use a ScrollViewer as the content host.
</TextBox>