WPF访问控件模板(ControlTemplate)内部的控件

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";
        }
复制代码

 

运行效果:

点击按钮后:

 

posted @   lxiamul  阅读(459)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示