代码之家  ›  专栏  ›  技术社区  ›  Sirop4ik

如何通过标记查找视图?

  •  0
  • Sirop4ik  · 技术社区  · 5 年前

    我有一个 Form 包含了一些 TableLayoutPanel

    每个 Lable 拉布勒 Name = "lable_name"

    Label 内部 .

    public void UpdateLable(string tag, string newText)
            {
                foreach(var tlp in Views)
                {
                    if (tlp.Tag.ToString().Equals(tag))
                    {
                        var lable = tlp.findViewByName("lable_name") as Label;
                        lable.Text = newText;
                    }
                }
            }
    

    但我找不到像 findViewByName()

    所以,问题是-如何按名称查找视图?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Lucifer    5 年前

    创建如下方法

    public static IEnumerable<Control> GetControlsOfType<T>(Control control)
    {
        var controls = control.Controls.Cast<Control>();
        return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl)).Concat(controls).Where(c => c is T);
    }
    

    Var control= GetControlsOfType<Label>(yourView).FirstOrDefault(x => x.Tag == tag);
    
    if(control != null)
       control.Text = newText
    
        2
  •  1
  •   Sirop4ik    5 年前

    没有直接在 TableLayoutPanel 班级。但是每一个 Control Controls 属性-子控件的集合。

    专门收集的 Find 方法,该方法允许按名称获取子级:

    var label = tlp.Controls.Find("lable_name", true)[0] as Label;
    
    推荐文章