• 关于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,这样就可以后台修改属性了。

  • 相关阅读:
    rdkit Recap、BRICS将smiles切分为片段(fragment)
    视频集中存储/直播点播平台EasyDSS点播文件分类功能新升级
    Redis 数据迁移篇之move、dump、migrate、redis-rdb-tools和redis-dump工具使用手册
    关系型数据库(二)---关系代数
    坦克车机器人操作学习总结开始篇
    NDK 是什么 | FFmpeg 5.0 编译 so 库
    [Linux 进程控制(二)] 进程程序替换
    [LeetCode] 最后一个单词的长度【58】
    ​力扣解法汇总934. 最短的桥
    App前端开发跨平台框架比较:React Native、Flutter、Xamarin等
  • 原文地址:https://blog.csdn.net/chulijun3107/article/details/126223637