如何:查找由 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 中的树