共用方式為


HOW TO:取代 TextBox 的預設內容裝載

更新:2007 年 11 月

本範例顯示如何使用 Windows Presentation Foundation (WPF) 樣式取代 TextBox 的預設內容裝載。

「內容裝載」是轉譯 TextBox 內容的項目。TextBox 的預設控制項樣板會指定 ScrollViewer 做為內容裝載。如需 TextBox 預設控制項樣板的範例,請參閱 TextBox ControlTemplate 範例

在不想要或不需要 ScrollViewer 所提供的捲動功能的情況下,輕量型的 AdornerDecorator 項目可以指定做為 TextBox 的內容裝載。

如需示範這個範例的運作範例,請參閱取代 TextBox 的預設內容裝載範例

範例

TextBoxControlTemplate 必須包含正好一個標記為內容裝載項目的項目。若要將項目標記為內容裝載,請指派特殊名稱 PART_ContentHost。內容裝載項目必須是 ScrollViewerAdornerDecorator。內容裝載項目無法裝載任何子項目。

下列可延伸標記語言 (XAML) 範例定義的樣式會覆寫 TextBox 的預設控制項樣板。這個樣式與 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 範例定義的 TextBox 會利用先前宣告的樣式,方法是使用 Style 屬性再加上對樣式 x:Key 屬性的靜態資源參考。

<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>

請參閱

概念

TextBox 概觀

RichTextBox 概觀

設定樣式和範本