方法 : ControlTemplate によって生成された要素を検索する

この例では、ControlTemplate によって生成された要素の検索方法について説明します。

使用例

次の例は、Button クラス用のシンプルな ControlTemplate を作成するスタイルを示しています。

<Style TargetType="{x:Type Button}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Grid Margin="5" Name="grid">
          <Ellipse Stroke="DarkBlue" StrokeThickness="2">
            <Ellipse.Fill>
              <RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5">
                <GradientStop Color="Azure" Offset="0.1" />
                <GradientStop Color="CornflowerBlue" Offset="1.1" />
              </RadialGradientBrush>
            </Ellipse.Fill>
          </Ellipse>
          <ContentPresenter Name="content" Margin="10"
                            HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

テンプレートの適用後にテンプレート内の要素を検索するには、TemplateFindName メソッドを呼び出します。 次の例は、コントロール テンプレート内にある Grid の実際の幅の値を表示するメッセージ ボックスを作成しています。

            ' Finding the grid that is generated by the ControlTemplate of the Button
            Dim gridInTemplate As Grid = CType(myButton1.Template.FindName("grid", myButton1), Grid)

            ' Do something to the ControlTemplate-generated grid
            MessageBox.Show("The actual width of the grid in the ControlTemplate: " & gridInTemplate.GetValue(Grid.ActualWidthProperty).ToString())
// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);

// Do something to the ControlTemplate-generated grid
MessageBox.Show("The actual width of the grid in the ControlTemplate: "
    + gridInTemplate.GetValue(Grid.ActualWidthProperty).ToString());

参照

処理手順

方法 : DataTemplate によって生成された要素を検索する

概念

スタイルとテンプレート

WPF XAML 名前スコープ

WPF のツリー