방법: 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
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());
' 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())

참고 항목