2

我的 WinForm 上有几个容器,如 Panel、SpliContainer、StatusStrip... 每个容器都包含基本元素,如按钮或文本框。我需要遍历所有表单控件(甚至是 Panels、SplitContainers、StatusStrip 中的控件)以找到一些控件。我尝试使用递归函数

    ListAllControls(Control MainControl)
    {
        foreach (Control control in MainControl.Controls)
        {
            if (control.HasChildren)
            {
                ListAllControls(control);
            }
            else
            { 
                // do something with this control
            }
        }
    }

但我没有得到容器中的控件!?

更新:

我有一个带有 SplitContainer、Panel 和 StatuStrip 的表单。在这些控件中的每一个中,我都有几个子控件,例如StatuStrip1 中的toolStripStatusLabel1。问题是当我尝试通过函数 ListAllControls 在StatuStrip 中找到例如控制工具StripStatusLabel1 时,我找不到它!?我不知道有任何其他方法可以从表单中获取所有控件。完整代码在这里:

class Control_Finder
{

    private Control founded_control = null;

    public Control Founded_Control
    {
        get { return founded_control; }
    }

    public void ListAllControls(Control MainControl, string SearchForControl)
    {
        foreach (Control control in MainControl.Controls)
        {
            if (control.HasChildren)
            {
                ListAllControls(control, SearchForControl);
            }
            else
            {
                // check if control has searched name
                if (control.Name == SearchForControl)
                {
                    founded_control = control;
                    return;
                }
            }
        }
    }
} // class

样本:

Form Me = this;
Control_Finder Test = new Control_Finder();
Test.ListAllControls(Me, "toolStripStatusLabel1");

if (Test.Founded_Control != null)
{
      MessageBox.Show("I found control " + Test.Founded_Control.Name + "!");
}
else
{
      MessageBox.Show("Didn't found! :(");
}

对于这个示例,我得到了没有找到:(但如果我使用 StatusStrip1,我会得到“我找到了控件 StatusStrip1!” 我希望现在的问题比以前更清楚。

4

1 回答 1

3

如果您提供一个良好的、最小的完整的代码示例来清楚地显示您的特定场景,那会更好。但是,根据您添加到问题中的信息,我能够创建我认为具有代表性的代码示例。该答案基于该示例。


正如评论者 LarsTech 指出的那样,ToolStripStatusLabel不继承Control. Control和共享的最具体的基类ToolStripStatusLabelComponent. 所以至少,你在尝试返回一个类型的对象Control但仍然找到一个ToolStripStatusLabel. 即使您确实找到了该对象,您也无法将其转换为Control.

另一个问题是,虽然ToolStrip它本身确实继承了Control类,但它不会将其子项存储在Controls属性中(即ControlCollection对象中)。我认为这是因为它的孩子不是Control对象,因此不能存储在ControlCollection. 无论如何,这意味着当您通过表单的对象图进行递归时,您必须以ToolStrip不同于其他实例的方式处理Control才能找到它的子对象。


这是一个示例程序,它演示了一种可行的方法(请参阅本文底部的 Designer 生成的代码,该代码与此示例一起使用):

Form1.cs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Component component = FindControl(this.Controls, "toolStripStatusLabel1");

        label2.Text = component != null ?
            "Found control named \"" + GetNameForComponent(component) + "\"" :
            "No control was found";
    }

    private static string GetNameForComponent(Component component)
    {
        Control control = component as Control;

        if (control != null)
        {
            return control.Name;
        }

        ToolStripItem item = component as ToolStripStatusLabel;

        if (item != null)
        {
            return item.Name;
        }

        return "<unknown Component type>";
    }

    private Component FindControl(IEnumerable controlCollection, string name)
    {
        foreach (Component component in controlCollection)
        {
            if (GetNameForComponent(component) == name)
            {
                return component;
            }

            IEnumerable childControlCollection = GetChildrenForComponent(component);

            if (childControlCollection != null)
            {
                Component result = FindControl(childControlCollection, name);

                if (result != null)
                {
                    return result;
                }
            }
        }

        return null;
    }

    private static IEnumerable GetChildrenForComponent(Component component)
    {
        ToolStrip toolStrip = component as ToolStrip;

        if (toolStrip != null)
        {
            return toolStrip.Items;
        }

        Control control = component as Control;

        if (control != null)
        {
            return control.HasChildren ? control.Controls : null;
        }

        return null;
    }
}

由于您正在处理的对象的对象继承性质不相交,因此必须进行一些特殊处理:

  1. 您找到的项目可能是实例,也可能Control不是。实例Control将其名称存储在Control.Name属性中,但显然不是Control对象的实例不会。它们需要通过识别存储它们的 name 属性的类型来专门处理(在这种情况下,ToolStripItem.Name,但请注意,还有其他非Control类型继承Component,每个类型都必须单独处理)。我添加了一个GetNameForComponent(Component)方法来封装它。
  2. 在您找到的属于 的实例的项目中Control,有些会将其子项存储在Controls集合中,而另一些则不会,而是使用其他一些属性来引用存储子项的集合。同样,提供了一个辅助方法(在本例中GetChildrenForComponent(Component)为 )来封装这种差异。

解决了这两个问题后,就可以轻松编写搜索图的基本递归方法。请注意,与您的相比,我对该方法的基本架构进行了一些更改。我认为将这段代码单独实现为一个完整的类是不必要的,并且无论如何将结果存储在该类的成员中而不是简单地由方法返回是特别错误的。

在我的示例中,我将它简单地实现为一个方法,如果找到,则返回相关对象。

另请注意,您的实现不会找到任何本身就是对象容器的对象。我也在我的例子中纠正了这一点。


最后一点:按照上述策略,您必须为每个感兴趣的基类添加代码。也许以上内容足以满足您的需求,或者您可能有其他包含非Control对象且不继承的容器类型ToolStrip。如果是这样,您将不得不在每个辅助方法中添加适合这些类型的额外案例。

另一种方法是使用反射来查找包含例如名称和子项的类成员。假设名称总是存储在一个名为 的属性中Name,那部分会相对简单。

但即使在这个简单的例子中,使用反射来获取孩子也是相当复杂的。而不是孩子总是在从名为 eg 的属性获得的集合对象中Controls,在一种情况下是名称,但在另一种情况下名称是Items。可以更深入地挖掘,例如确定在集合中找到的对象的类型,但此时代码开始变得过于复杂。

ToolStrip鉴于无论如何以某种形式将儿童与普通儿童一样对待是否真的有意义是有争议Control的,我不建议在真正通用的解决方案上投入太多精力。最好根据需要处理个别情况,提醒自己你所做的首先并不是一个好主意。:)


Form1.Designer.cs:

partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.statusStrip1 = new System.Windows.Forms.StatusStrip();
        this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
        this.button1 = new System.Windows.Forms.Button();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.statusStrip1.SuspendLayout();
        this.SuspendLayout();
        // 
        // statusStrip1
        // 
        this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
        this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.toolStripStatusLabel1});
        this.statusStrip1.Location = new System.Drawing.Point(0, 228);
        this.statusStrip1.Name = "statusStrip1";
        this.statusStrip1.Size = new System.Drawing.Size(282, 25);
        this.statusStrip1.TabIndex = 0;
        this.statusStrip1.Text = "statusStrip1";
        // 
        // toolStripStatusLabel1
        // 
        this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
        this.toolStripStatusLabel1.Size = new System.Drawing.Size(111, 20);
        this.toolStripStatusLabel1.Text = "Strip status text";
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(12, 12);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(12, 38);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(52, 17);
        this.label1.TabIndex = 2;
        this.label1.Text = "Result:";
        // 
        // label2
        // 
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(70, 38);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(0, 17);
        this.label2.TabIndex = 3;
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(282, 253);
        this.Controls.Add(this.label2);
        this.Controls.Add(this.label1);
        this.Controls.Add(this.button1);
        this.Controls.Add(this.statusStrip1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.statusStrip1.ResumeLayout(false);
        this.statusStrip1.PerformLayout();
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.StatusStrip statusStrip1;
    private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
}
于 2015-09-30T04:23:29.477 回答