방법: 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의 트리