从usercontrol访问父控件 [英] Getting access to parent controls from a usercontrol

查看:124
本文介绍了从usercontrol访问父控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从用户控件访问父控件

- 在我的主窗体(Form1)中,我有一个listBox(listBox1)

-I还添加了一个用户控件(UserControl1)到我的项目

-在userControl上,我添加了一个按钮(Button1)

我要做的是点击按钮,文本被添加到listBox1

尝试了几种选择,但我还没有成功。



我尝试了什么:



试图将此代码添加到usercontrol中的button1

ListBox listBox =(ParentForm.Controls [listBox1]为ListBox); listBox.Items.Add( 测试);

//没有运气



还添加了获取/设置

公共部分类userControl1:UserControl

public Form1 ParentForm {get; set}



按钮,我也试过

控制p =这个。 ParentForm;

ListBox listBox =(ParentForm.Controls [listBox1]如ListBox);

listBox.Items.Add(Test);

//没有运气

Getting access to parent controls from a usercontrol
-In my main form (Form1), I have a listBox (listBox1)
-I also added a user control (UserControl1) to my project
-On the userControl, I added a button (Button1)
What I want to do is click on button and text is added to the listBox1
Tried several options but I have not been sucessfull.

What I have tried:

tried to add this code to the button1 in the usercontrol
ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox); listBox.Items.Add("Test");
//No luck

also added the get/set
public Partial Class userControl1 : UserControl
public Form1 ParentForm {get;set}

for the button, I also tried
Control p = this.ParentForm;
ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox);
listBox.Items.Add("Test");
//no luck

推荐答案

您的UserControl应该永远不关心持有UserControl的容器中的任何控件。它永远不应该想要操纵UserControl本身之外的任何控件。



为什么?因为一旦你这样做,你永远将你的控制与其他控件的存在联系在一起,这要求控制之外的控件被使用并确切命名UserControl的预期。



绝对不要这样做!



相反,当您单击按钮时,会显示UserControl中的事件。您的事件的事件参数应包含您要传输给其他控件的数据。



现在,父表单或容器可以订阅该事件并决定如何处理数据本身,例如在父窗体的控制下将其添加到ListBox。
Your UserControl should NEVER care about any controls that are in the container holding your UserControl. It should never want to manipulate any controls outside of the UserControl itself.

Why? Because once you do that, you forever tie your control to the existence of other controls, making it a requirement that controls outside your control be used and named exactly how the UserControl expects.

NEVER DO THIS!

Instead, expose an event from your UserControl that is raised when you click the button. The event args of your event should contain the data that you want to transmit to some other control.

Now, the parent form or container can subscribe to the event and decide what to do with the data itself, such as adding it to a ListBox under the control of the parent form.


这篇关于从usercontrol访问父控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆