How to: Find ControlTemplate-Generated Elements


This example shows how to find elements that are generated by a ControlTemplate.


The following example shows a style that creates a simple ControlTemplate for the Button class:

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

To find an element within the template after the template has been applied, you can call the FindName method of the Template. The following example creates a message box that shows the actual width value of the Grid within the control template:

' 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())