简体   繁体   English

C#如何获取控制哪个修饰符是私有的

[英]c# how to get control which modifier is private

i have a custom control in a form which is private . 我有一个private形式的自定义控件。

In the other form i have code like this 在另一种形式中,我有这样的代码

foreach(Form f in Application.OpenForms)

one of the forms is Formthatcontaincontrols , 形式之一是Formthatcontaincontrols

Formthatcontaincontrols contains the custom control which is private , i need to access that customcontrol from form "f" Formthatcontaincontrols包含private的自定义控件,我需要从形式"f"访问该customcontrol

You could expose the control via public property: 您可以通过公共属性公开控件:

In Formthatcontaincontrols Formthatcontaincontrols

public TheCustomControlYouWant TheCustomControl
{
    get { return this.CustomControl; }
}

Then you can access this property: 然后,您可以访问此属性:

foreach(Formthatcontaincontrols f in Application.OpenForms.OfType<Formthatcontaincontrols>())
{
    TheCustomControlYouWant ctrl = f.TheCustomControl;
}

Please do not expose implementation details when using controls. 使用控件时,请不要公开实现细节。

From the perspective of the consumer of your parent custom control ( Formthatcontaincontrols ), implementation details should be hidden. 从父级自定义控件( Formthatcontaincontrols )的使用者的角度来看,应该隐藏实现细节。

I assume you need to access some kind of property which is important for the consumer of the Formthatcontaincontrols . 我假设您需要访问某种属性,这对于包含Formthatcontaincontrols的使用者很重要。

I advise just to expose this property and let the control itself find the relevant child and access the inner property defined in the child control. 我建议仅公开此属性,并让控件本身找到相关的子代并访问该子代控件中定义的内部属性。

You can find Formthatcontaincontrols using the solution pasted by @Tim Schmelter. 你可以找到Formthatcontaincontrols使用@Tim Schmelter粘贴的解决方案。

You can explore all the controls in the form: 您可以浏览以下形式的所有控件:

private List<T> FindControls<T>(Control.ControlCollection controls) where T: Control
{
    List<T> list = new List<T>();
    foreach (Control control in controls)
    {
        var matched = control as T;
        if (matched != null)
            list.Add(matched);
        else
            list.AddRange(FindControls<T>(control.Controls));
    }
    return list;
}

For example, you can search all buttons with this: 例如,您可以使用以下命令搜索所有按钮:

foreach (var btn in FindControls<Button>(yourForm.Controls))
{
    Trace.WriteLine(btn.Name);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM