母版页/aspx 页面如何侦听在另一个用户控件内的用户控件中调度的事件
我有一个母版页和一个 aspx 页面。 我希望它们每个人都侦听从内部用户控件分派的事件(意味着用户控件不在页面本身中,而是在另一个用户控件内)?
角色转换会更容易吗?这意味着内部控件将通知它的母版页? 我看到了这个: 帮助c#事件监听和用户控件
但我的问题更复杂思考。
I have a master page and an aspx page.
I want each of them to listen to an event that is dispatched from a inner user control (meaning a user-control which is not in the page itself, but inside another user-control) ?
Would it be easier to switch roles? meaning the inner control will notify it's master page ?
I saw this:
Help with c# event listening and usercontrols
but my problem is more complicated I think.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以沿着页面的路线递归通过其控件来找到 UserControl 并附加到它的 EventHandler,这是最简单、最直接的方法。
这需要更多的工作,但我喜欢单个事件总线的想法,您的页面可以使用它来注册为特定事件的观察者(无论谁发送它)。然后,您的 UserControl 也可以通过此发布事件。这意味着链的两端仅依赖于事件(和总线,或总线的接口),而不是特定的发布者/订阅者。
您需要小心线程安全并确保您的控件正确共享事件总线。我相信 ASP.NET WebForms MVP 项目采用了这种方法,您可以看看。
You could go down the route of the pages recursing through their controls to find the UserControl and attach to the EventHandler of it which is the simplest and most straight-forward way.
It's a bit more work, but I like the idea of a single Event Bus that your pages can use to register as observers of a particular event (regardless of who sends it). Your UserControl can then also publish the events through this. This means that both ends of the chain are just dependent on the event (and the bus, or an interface of one), rather than a specific publisher / subscriber.
You would need to be careful with thread-safety and making sure your controls share the Event Bus correctly. I believe the ASP.NET WebForms MVP project takes this approach which you could look at.
尝试使用以下方法:
在 UserControl 中定义一个事件
通过递归控件集合并附加事件处理程序在页面/主加载方法中查找 UserControl
希望这会有所帮助。
Try using the following approach:
Define an event in your UserControl
Find the UserControl in your Page/Master Load methods by recursing the controls collection and attaching an event handler
Hope this helps.