ControlTemplate 定义的控件一般情况外部是无法访问的 ,由 ControlTemplate 或 DataTemplate 生成的控件都是“ 由 Template 生成的控件 ”。
ControlTemplate 和 DataTemplate 两个类均派生自 FrameworkTemplate 类,这个类有个名为 FindName 的方法供我们检索其内部控件。也就是说,只要我们能拿到 Template,找到其内部控件就不成问题。对于ControlTemplate对象,访问其目标控件的Template属性就能拿到。
<Window.Resources>
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Height" Value="100"/>
<Setter Property="Width" Value="200"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="text1" Text="111" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18"/>
<TextBlock x:Name="text2" Text="222" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" Grid.Column="1"/>
<TextBlock x:Name="text3" Text="333" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" Grid.Row="1"/>
<TextBlock x:Name="text4" Text="444" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" Grid.Row="1" Grid.Column="1"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="#FF8AABF8"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button x:Name="btn" Style="{DynamicResource ButtonStyle}" Click="Button_Click"/>
</Grid>
后台C#代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
TextBlock text = this.btn.Template.FindName("text1", this.btn) as TextBlock;//查找与此模板中定义的指定名称关联的元素
text.Text = "One";
Grid grid = text.Parent as Grid;//获取模板内(text)控件的逻辑父元素
(grid.Children[1] as TextBlock).Text = "Two";
(grid.Children[2] as TextBlock).Text = "Three";
(grid.Children[3] as TextBlock).Text = "Four";
}
运行效果:
点击按钮后: