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

  • 相关阅读:
    elasticsearch5.6设置用户名密码
    使用knuth Durstenfeld Shuffle置乱关键区域
    【MATLAB】MATLAB App Designer中的回调函数
    SQL基本语句
    JWFD开源工作流-矩阵大模型的最新进展
    基于RRT算法的最优动力学路径规划(Matlab代码实现)
    雅思口语同替高分表达
    create-vite‘ 不是内部或外部命令,也不是可运行的程序
    最全“Java面试宝典+Java核心知识集”,一箭双雕杠秋招
    2023年入职/转行网络安全,该如何规划?
  • 原文地址:https://blog.csdn.net/chulijun3107/article/details/126223637