Partager via


Rechercher des éléments générés par ControlTemplate

Cet exemple montre comment rechercher des éléments qui sont générés par ControlTemplate.

Exemple

L'exemple suivant montre un style qui crée un ControlTemplate simple pour la classe Button :

<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>

Pour rechercher un élément dans le modèle une fois que celui-ci a été appliqué, vous pouvez appeler la méthode FindName du Template. L'exemple suivant crée un message qui affiche la largeur réelle de la Grid dans le modèle de contrôle :

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

Voir aussi

Tâches

Comment : rechercher des éléments générés par DataTemplate

Concepts

Application d'un style et création de modèles

Portées de nom XAML WPF

Arborescences dans WPF