跨用户控制通信 [英] Cross User Control Communication

查看:94
本文介绍了跨用户控制通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果页面上有2个用户控件,并且UserControl1_Button的单击事件应设置UserControl2_Label的值(例如Text).怎么可能?我arleady尝试使用base.Parent.FindControl.它只能转到上级控件.

If we have 2 user controls on a page, and on click event of UserControl1_Button should set value (say Text) of UserControl2_Label. How is it posible? I arleady tried with using base.Parent.FindControl. It can go only upto Parent controls.

推荐答案

即使您找到了实现此目的的方法,也将是不好的设计.

1. UserControl1知道UserControl2的实现详细信息.那是不好的设计.您应该针对接口进行编程,而不是针对实现进行编程.
2.最好让我们放弃将UserControl2的标签更改为自己的任务.

在UserControl1中定义一个事件.单击UserControl1的特定按钮时,触发事件.然后另一个控件应该能够侦听该事件并执行它想要的任何操作.

这种方法的好处:

1.无论UserControl2的代码发生什么变化,UserControl1都无需更改.
2.您也可以将UserControl1的按钮单击事件重用于其他GUI对象.
Even if you find a way to do this, it will be bad design.

1. UserControl1 is aware of UserControl2''s implementation details. That''s bad design. You should program against an interface, not against implementation.
2. It would be better if we can leave the task of changing UserControl2''s label to itself.

Define an event in UserControl1. Fire the event when that particular button of UserControl1 is clicked. Then the other control should be able to listen to that event and perform any action it wants.

Benefits of this approach:

1. No matter what happens to UserControl2''s code, UserControl1 need not to change.
2. You can reuse the button click event of UserControl1 for other GUI objects as well.


在父"页面中查找UserControl2,然后在UserControl2中查找Label控件. 这是解决方案.将尽快发布可靠的解决方案.

Find UserControl2 in Parent page and then Find Label control inside UserControl2 .
Here is the solution. Will post robust solution asap.



protected void Button1_Click(object sender, EventArgs e)
{
      UserControl  uc = base.Parent.FindControl("uc2") as UserControl;
       if (uc != null)
       {
         uc.FindControl("lblUserControl2") as Label).Text  = "its from usercontrol1 Button click event ";
       }
}


这篇关于跨用户控制通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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