[英]consuming custom event of one user control in another user control?
In UserControl1 there is a custom event which I want to wire in UserControl2. 在UserControl1中,有一个自定义事件,我想在UserControl2中进行连接。
in UserControl1 I have declared the custom event as: 在UserControl1中,我将自定义事件声明为:
public event MYDelegate SendMessage;
while my delegate defination is in other class library as: 而我的委托人定义在其他类库中为:
public delegate string MYDelegate(string message);
I am firing SendMessage in my code as below: 我在我的代码中触发了SendMessage,如下所示:
SendMessage(txt.Text);
Kindly guide me how to wire SendMessage() event in UserControl2. 请指导我如何在UserControl2中连接SendMessage()事件。 My idea was do something like in below example but not sure how to get/ access UserControl1 object in UserControl2. 我的想法是执行以下示例中的操作,但是不确定如何在UserControl2中获取/访问UserControl1对象。
Please help me. 请帮我。
UserControl1.SendMessge+=ListnerMetod();
You are almost there. 你快到了 You just need to attach SendMessage to UserControl2's ListnerMetod. 您只需要将SendMessage附加到UserControl2的ListnerMetod。
As Mark Hall said, it is not a good practice to fire an event from one control to another without parent page knowing. 正如Mark Hall所说,在父页面未知的情况下,将事件从一个控件触发到另一个控件不是一个好习惯。
Here is the sample code of firing an event through a parent page. 这是通过父页面触发事件的示例代码。
<%@ Register Src="SenderUserControl.ascx" TagName="SenderUserControl"
TagPrefix="uc1" %>
<%@ Register Src="ReceiverUserControl.ascx" TagName="ReceiverUserControl"
TagPrefix="uc2" %>
<uc1:SenderUserControl ID="SenderUserControl1" runat="server" />
<uc2:ReceiverUserControl ID="ReceiverUserControl1" runat="server" />
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
SenderUserControl1.SendMessage += m => ReceiverUserControl1.ListnerMethod(m);
}
}
public delegate void MessageHandler(string message);
public partial class SenderUserControl : System.Web.UI.UserControl
{
public event MessageHandler SendMessage;
protected void Button1_Click(object sender, EventArgs e)
{
SendMessage("test");
}
}
public partial class ReceiverUserControl : System.Web.UI.UserControl
{
public void ListnerMethod(string message)
{
}
}
如果两个UserControl都由同一父控件承载,则将父控件中的处理程序附加到要订阅的UserControls事件,然后在该处理程序的第二个UserControl中调用一个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.