次の方法で共有


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

更新 : 2007 年 11 月

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

コンテンツ ホストは、RichTextBox のコンテンツをレンダリングする要素です。RichTextBox の既定のコントロール テンプレートは、コンテンツ ホストとして ScrollViewer を指定します。

ScrollViewer のスクロール機能が不要な場合は、軽量の AdornerDecorator 要素を RichTextBox のコンテンツ ホストとして指定できます。ScrollViewer および AdornerDecorator は、コンテンツ ホストでサポートされる唯一の要素です。

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

使用例

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

次の Extensible Application Markup Language (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>

参照

概念

RichTextBox の概要

TextBox の概要

スタイルとテンプレート