C# 根据name查找并返回winform菜单栏(MenuStrip)、工具栏(ToolStrip)中的子控件来修改属性

winform中可以在窗体的类中通过this.Controls.Find(控件的name, true).FirstOrDefault();函数 来实现用name查找页面中所有子控件,并可以用来修改该控件的属性。但是菜单栏和工具栏中的子控件是查找不到的 ,++因为这菜单栏和工具栏中的按钮和文本等子控件不是继承自Control ,它们分别是继承自ToolStripMenuItemToolStripItem++ **。**所以不能作为Control被检索到,因此需要单独为菜单栏和工具栏写一个查找子控件的函数,以实现对大量控件的查找和修改。

一、实际使用场景

++复杂界面中所有控件文字的热重载中英文切换++,根据name查找到指定控件并切换它的text。

二、函数源码

递归方法查找并修改 MenuStrip及其子项中的子项的 Text

cs 复制代码
/// <summary>
/// 递归方法查找并修改 MenuStrip 及其子项中的子项的 Text
/// </summary>
/// <param name="items">MenuStrip.Items</param>
/// <param name="name">控件的name</param>
/// <param name="textValue">修改的text值</param>
private void SetMenuStripControl( ToolStripItemCollection items, string name, string textValue)
{
    foreach (ToolStripItem item in items)
    {
        if (item is ToolStripMenuItem menuItem)
        {
            if (item.Name == name)
            {
                // 修改 Text 属性
                item.Text = textValue;
            }
            // 递归查找子项中的子项
            SetMenuStripControl( menuItem.DropDownItems, name, textValue);
        }
    }
}

递归方法查找并修改 ToolStrip及其子项中的子项的 Text

cs 复制代码
/// <summary>
/// 递归方法查找并修改 ToolStrip 及其子项中的子项的 Text
/// </summary>
/// <param name="items"></param>
/// <param name="name"></param>
/// <param name="textValue"></param>
private void SetToolStripControl(ToolStripItemCollection items, string name, string textValue)
{
    foreach (ToolStripItem item in items)
    {
        var it = item;
        if (item.Name == name)
        {
            // 修改 Text 属性
            item.Text = textValue;
        }
        if (item is ToolStripDropDownItem dropDownItem)
        {
            // 递归查找子项中的子项
            SetToolStripControl(dropDownItem.DropDownItems, name, textValue);
        }
    }
}
相关推荐
hez201020 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题3 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说3 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox