简体   繁体   English

从用户控件获取对父控件的访问权限 - C#

[英]Get access to parent control from user control - C#

How do I get access to the parent controls of user control in C# (winform).如何在 C# (winform) 中访问用户控件的父控件。 I am using the following code but it is not applicable on all types controls such as ListBox.我正在使用以下代码,但它不适用于所有类型的控件,例如 ListBox。

Control[] Co = this.TopLevelControl.Controls.Find("label7", true);
Co[0].Text = "HelloText"

Actually, I have to add items in Listbox placed on parent 'Form' from a user control.实际上,我必须在用户控件的父“表单”上的列表框中添加项目。

Description描述

You can get the parent control using Control.Parent .您可以使用Control.Parent获取父控件。

Sample样本

So if you have a Control placed on a form this.Parent would be your Form.因此,如果您在表单上放置了一个控件this.Parent将是您的表单。

Within your Control you can do在您的控制范围内,您可以做到

Form parentForm = (this.Parent as Form);

More Information更多信息

Update after a comment by Farid-ur-Rahman ( He was asking the question )在 Farid-ur-Rahman 发表评论后更新(他在问这个问题

My Control and a listbox (listBox1) both are place on a Form (Form1).我的控件和列表框 (listBox1) 都放在表单 (Form1) 上。 I have to add item in a listBox1 when user press a button placed in my Control.当用户按下放置在我的控件中的按钮时,我必须在 listBox1 中添加项目。

You have two possible ways to get this done.您有两种可能的方法来完成这项工作。

1. Use `Control.Parent 1.使用`Control.Parent

Sample样本

MyUserControl我的用户控件

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Parent == null || this.Parent.GetType() != typeof(MyForm))
            return;

        ListBox listBox = (this.Parent as MyForm).Controls["listBox1"] as ListBox;
        listBox.Items.Add("Test");
    }

or要么

2. 2.

  • put a property public MyForm ParentForm { get; set; }把一个属性public MyForm ParentForm { get; set; } public MyForm ParentForm { get; set; } public MyForm ParentForm { get; set; } to your UserControl public MyForm ParentForm { get; set; }到你的UserControl
  • set the property in your Form在您的表单中设置属性
  • assuming your ListBox is named listBox1 otherwise change the name假设您的ListBox名为listBox1否则更改名称

Sample样本

MyForm我的表格

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();
        this.myUserControl1.ParentForm = this;
    }
}

MyUserControl我的用户控件

public partial class MyUserControl : UserControl
{
    public MyForm ParentForm { get; set; }

    public MyUserControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (ParentForm == null)
            return;

        ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox);
        listBox.Items.Add("Test");

    }
}

You can use Control.Parent to get the parent of the control or Control.FindForm to get the first parent Form the control is on.您可以使用Control.Parent得到控制或父Control.FindForm拿到的第一个父Form的控制上。 There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:两者在查找形式方面存在差异,因此一种可能比另一种更适合使用:

The control's Parent property value might not be the same as the Form returned by FindForm method.控件的 Parent 属性值可能与 FindForm 方法返回的 Form 不同。 For example, if a RadioButton control is contained within a GroupBox control, and the GroupBox is on a Form, the RadioButton control's Parent is the GroupBox and the GroupBox control's Parent is the Form.例如,如果 RadioButton 控件包含在 GroupBox 控件中,而 GroupBox 位于窗体上,则 RadioButton 控件的父级是 GroupBox,而 GroupBox 控件的父级是窗体。

Control has a property called Parent, which will give the parent control.控件有一个名为 Parent 的属性,它将赋予父控件。 http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

eg Control p = this.Parent;例如Control p = this.Parent;

A generic way to get a parent of a control that I have used is:获取我使用过的控件的父级的通用方法是:

public static T GetParentOfType<T>(this Control control)
{
    const int loopLimit = 100; // could have outside method
    var current = control;
    var i = 0;

    do
    {
        current = current.Parent;

        if (current == null) throw new Exception("Could not find parent of specified type");
        if (i++ > loopLimit) throw new Exception("Exceeded loop limit");

    } while (current.GetType() != typeof(T));

    return (T)Convert.ChangeType(current, typeof(T));
}

It needs a bit of work (eg returning null if not found or error) ... but hopefully could help someone.它需要一些工作(例如,如果未找到或出错则返回 null)...但希望可以帮助某人。

Usage:用法:

var parent = currentControl.GetParentOfType<TypeWanted>();

Enjoy!享受!

You can get the Parent of a control via您可以通过以下方式获取控件的父级

myControl.Parent

See MSDN: Control.Parent请参阅 MSDN: Control.Parent

Not Ideal, but try this...不理想,但试试这个......

Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)将用户控件更改为组件类(在代码编辑器中),构建解决方案并删除所有有错误的代码(与用户控件相关,但在组件中不可用,因此调试器会抱怨)

Change the usercontrol back to usercontrol class...将用户控件更改回用户控件类...

Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.现在它可以识别名称和父属性,但将组件显示为不可见,因为它不再是可设计的。

According to Ruskins answer and the comments here I came up with the following (recursive) solution:根据拉斯金斯的回答和这里的评论我想出了以下(递归)解决方案:

public static T GetParentOfType<T>(this Control control) where T : class
{
    if (control?.Parent == null)
        return null;

    if (control.Parent is T parent)
        return parent;

    return GetParentOfType<T>(control.Parent);
}
((frmMain)this.Owner).MyListControl.Items.Add("abc");

确保在frmMain MyListControl Private 以外的 Modifiers 属性中提供您想要的访问级别

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:如果您想通过任何子控件获取任何父控件,您可以使用此代码,当您找到UserControl/Form/Panel或其他控件时,您可以调用函数或设置/获取值:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}

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

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