从usercontrol按钮调用表单按钮 [英] Invoke a form button from usercontrol button

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

问题描述

我在我的C#项目中添加了一个usercontrol,并在usercontrol中添加了一个buttonsX。

在我的主窗体中,我有一个按钮Y,它也填充了主窗体中的列表框。

如何从buttonX调用buttonY?



我尝试过:



试图学习invoke方法,但它非常复杂

解决方案

简单。你没有。



你所描述的问题是你将UserControl永远绑在表格上。它将无法以任何其他形式使用。控件应该永远不知道任何事情或想要对父容器(表单或其他控件)做任何事情。控件只负责自己的内容和代码。



那你怎么做?您的UserControl应该公开您的按钮代码引发的事件。父表单或其他包含控件可以订阅此事件并决定在引发事件时要执行的操作,例如,运行该按钮代码,甚至忽略该事件。



您所描述的另一个问题是您要运行的Button Click处理程序中的代码不应位于Button Click事件处理程序中。该代码应该在它自己的方法中,使得从Button Click事件处理程序和Form代码中的任何其他位置调用它非常容易,甚至是UserControl Button事件的事件处理程序。


< blockquote>

 //用户控制按钮单击事件
private void buttonsX_Click(object sender,EventArgs e)
{
Button parentFormButtonY =(Button)this.ParentForm.Controls。查找(buttonsY,true)[0];
parentFormButtonY.PerformClick();

}


I added a usercontrol to my C# project and added a buttonsX to the usercontrol.
In my main form, I have a buttonY that populates a listbox also in the main form.
How can I invoke the buttonY from buttonX?

What I have tried:

trying to learn the invoke method but it is very complex

解决方案

Simple. You don't.

The problem with what you're describing is that you're tying the UserControl to the form forever. It will not be able to be used in any other form. Controls should NEVER know anything or want to do anything with the parent container (Form or other controls). Controls are responsible only for their own content and code.

So how do you do this? Your UserControl should expose an event that your button code raises. The parent form, or other containing control, can subscribe to this event and decide what to do when the event is raised, for example, running that button code, or even ignoring the event.

The other problem with what you describe is that the code in the Button Click handler that you want to run should not be in the Button Click event handler. That code should be in its own method, making it very easy to call it from both the Button Click event handler AND anywhere else in the Form code, even the event handler for your UserControl Button event.


// user control button click event
       private void buttonsX_Click(object sender, EventArgs e)
       {
           Button parentFormButtonY = (Button) this.ParentForm.Controls.Find("buttonsY", true)[0];
           parentFormButtonY.PerformClick();

       }


这篇关于从usercontrol按钮调用表单按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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