次の方法で共有


方法 : TextBox の既定コンテンツ ホストを置き換える

更新 : 2007 年 11 月

ここで示す例では、TextBox の既定のコンテンツ ホストに代わる Windows Presentation Foundation (WPF) のスタイルを使用する方法を示します。

コンテンツ ホストは、TextBox のコンテンツをレンダリングする要素です。TextBox の既定のコントロール テンプレートは、コンテンツ ホストとして ScrollViewer を指定します。TextBox の既定のコントロール テンプレートの例については、「TextBox ControlTemplate の例」を参照してください。

ScrollViewer のスクロール機能が不要な場合は、軽量の AdornerDecorator 要素を TextBox のコンテンツ ホストとして指定できます。

この例の具体的なサンプルについては、「TextBox の既定コンテンツ ホストの置き換えのサンプル」を参照してください。

使用例

TextBoxControlTemplate には、コンテンツ ホスト要素であることが示された要素を 1 つだけ含める必要があります。要素がコンテンツ ホストであることを示すには、その要素に特別な名前「PART_ContentHost」を付けます。コンテンツ ホスト要素は、ScrollViewer または AdornerDecorator でなければなりません。コンテンツ ホスト要素で子要素をホストすることはできません。

次の Extensible Application Markup Language (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 の例では、Style 属性とスタイルの x:Key 属性への静的なリソース参照を組み合わせて使用することによって、宣言済みのスタイルを利用する TextBox を定義しています。

<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 の概要

スタイルとテンプレート