• 关于WPF template使用FindName查找控件方法问题。


    这个方法在Window内使用是没有问题的。代码如下:

    1. "WpfApp1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:WpfApp1"
    7. mc:Ignorable="d"
    8. Title="MainWindow" Height="450" Width="800" Background="Yellow">
    9. "RecFill" Color="Red">
    10. "RecStroke" Color="LightBlue">

    后台代码:

    1. private void Button_Click(object sender, RoutedEventArgs e)
    2. {
    3. TextBlock text = this.btn.Template.FindName("text1", this.btn) as TextBlock;//查找与此模板中定义的指定名称关联的元素
    4. text.Text = "One";
    5. Grid grid = text.Parent as Grid;//获取模板内(text)控件的逻辑父元素
    6. (grid.Children[1] as TextBlock).Text = "Two";
    7. (grid.Children[2] as TextBlock).Text = "Three";
    8. (grid.Children[3] as TextBlock).Text = "Four";
    9. }

    显示结果:

    可是如果这个方法在UserControl中使用,是找不到模板中的控件的。

    1. //
    2. // 摘要:
    3. // 查找与此模板中定义的指定名称关联的元素。
    4. //
    5. // 参数:
    6. // name:
    7. // 字符串名称。
    8. //
    9. // templatedParent:
    10. // 应用此模板的 System.Windows.FrameworkElement 的上下文。
    11. //
    12. // 返回结果:
    13. // 与指定名称关联的元素。
    14. public object FindName(string name, FrameworkElement templatedParent);

     原因是控件初始化时还未生成,如果想占用这种方法设置ControlTtemplate中的属性。要把它放到Load方法中。这么使用就可以了。

     函数中已找到模板中的Button,这样就可以后台修改属性了。

  • 相关阅读:
    Ims服务架构
    A. Morning Sandwich
    [题] 筛质数 #质数(素数)
    使用搭载骁龙 8 Gen 3 的安卓手机运行 AI 大模型
    阿里巴巴面试题- - -JVM篇(十九)
    HTML5+CSS3+JS小实例:使用L2Dwidget实现二次元卡通看板娘
    CSS实现鼠标悬停图片上升显示
    KT148A语音芯片常见问题集锦|硬件|软件以及注意事项-长期更新
    【无标题】
    正则表达式——4.贪婪与非贪婪搜寻、特殊字符
  • 原文地址:https://blog.csdn.net/chulijun3107/article/details/126223637