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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8820606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:37:57  来源:igfitidea点击:

Get access to parent control from user control - C#

c#winformsuser-controls

提问by Farid-ur-Rahman

How do I get access to the parent controls of user control in C# (winform). I am using the following code but it is not applicable on all types controls such as ListBox.

如何在 C# (winform) 中访问用户控件的父控件。我正在使用以下代码,但它不适用于所有类型的控件,例如 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.

实际上,我必须在用户控件的父“表单”上的列表框中添加项目。

采纳答案by dknaack

Description

描述

You can get the parent control using Control.Parent.

您可以使用Control.Parent.

Sample

样本

So if you have a Control placed on a form this.Parentwould 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). I have to add item in a listBox1 when user press a button placed in my Control.

我的控件和列表框 (listBox1) 都放在表单 (Form1) 上。当用户按下放置在我的控件中的按钮时,我必须在 listBox1 中添加项目。

You have twopossible 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; }to your UserControl
  • set the property in your Form
  • assuming your ListBoxis named listBox1otherwise change the name
  • public MyForm ParentForm { get; set; }给你的财产UserControl
  • 在您的表单中设置属性
  • 假设您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");

    }
}

回答by keyboardP

You can use Control.Parentto get the parent of the control or Control.FindFormto get the first parent Formthe control is on. There is a difference between the two in terms of finding forms, so one may be more suitable to use than the other.:

您可以使用Control.Parent得到控制或父Control.FindForm拿到的第一个父Form控件上。两者在查找形式方面存在差异,因此一种可能比另一种更适合使用:

The control's Parent property value might not be the same as the Form returned by FindForm method. 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.

控件的 Parent 属性值可能与 FindForm 方法返回的 Form 不同。例如,如果 RadioButton 控件包含在 GroupBox 控件中,并且 GroupBox 位于窗体上,则 RadioButton 控件的父级是 GroupBox,而 GroupBox 控件的父级是窗体。

回答by chaosr

You can get the Parent of a control via

您可以通过以下方式获取控件的父级

myControl.Parent

See MSDN: Control.Parent

请参阅 MSDN: Control.Parent

回答by Sprintstar

Control has a property called Parent, which will give the parent control. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

控件有一个名为 Parent 的属性,它将赋予父控件。http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

eg Control p = this.Parent;

例如 Control p = this.Parent;

回答by Tery Aldon

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.

现在它可以识别名称和父属性,但将组件显示为不可见,因为它不再是可设计的。

回答by Asaf

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControlat frmMain

确保提供接入水平,你想比其他私人性质改性剂用于MyListControlfrmMain

回答by daniele3004

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panelor others you can call funnctions or set/getvalues:

如果您想通过任何子控件获取任何父控件,您可以使用此代码,当您找到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";
        }
    }

}

回答by Ruskin

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 (e.g. returning null if not found or error) ... but hopefully could help someone.

它需要一些工作(例如,如果未找到或出错则返回 null)...但希望可以帮助某人。

Usage:

用法:

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

Enjoy!

享受!

回答by Christian Junk

According to Ruskins answer and the comments hereI 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);
}