ASP.NET 用户控制交叉通信
场景:2 个用户控件(foo.ascx 和 fum.ascx)
foo 有一个确实想从 fum 访问属性的方法。 他们生活在同一页上,但我找不到一种非常简单的方法来完成这种通信。
有任何想法吗?
The scenario: 2 user controls (foo.ascx and fum.ascx)
foo has a method that would really like to access a property from fum. They live on the same page, but I can't find a very simple way to accomplish this sort of communication.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
OnMyPropertyValueChanged
。OnMyPropertyValueChanged
in fum.ascx.有几种方法可以解决这个问题,但最好的解决方案是尽可能解耦。
最解耦的方法是递归 findControl 方法,它遍历控件对象模型,直到找到所需的控件并返回引用。
这是另一种有点简洁的方法,尽管我不知道是否会使用它。(有点伪代码):
从 FunkyUserControl 继承两个用户控件,然后在主页面类中您可以执行以下操作:
现在每个控件都可以内省其订阅者集合来查找其他控件。
There are a few ways to handle this, but optimally you want a solution that is as decoupled as possible.
The most decoupled method would be a recursive findControl method that walks the control object model until it finds the control you want and returns a reference.
Here is another approach that is kinda neat, though I don't know if I'd use it.(Somewhat pseudocode):
Inherit your two usercontrols from FunkyUserControl and then in your main page class you can do:
Now each control can introspect its subscribers collection to find the other control.
将事件添加到连接到窗体的 UserControl。
Add an event to the UserControl that is hooked up to the form.
最简单的解决方案是 fum 在 HttpContext.Current.Items[] 中存储一个值,foo 稍后可以在其中读取它。
一个更强大的选项是为 foo 提供一个属性,页面可以使用对 fum 的引用来填充该属性。
活动的工作量更大,但架构上更好。
The simplest solution is for fum to store a value in HttpContext.Current.Items[], where foo can read it later.
A more robust option is to give foo a property that the the page can populate with a reference to fum.
An event is more work, but is architecturally nicer.
您可以通过在
Foo 的 Parent
上使用FindControl
来引用其他用户控件。 这是最简单的,您不需要在每个主(父)表单上进行任何编程。You can reference the other user control by using
FindControl
onFoo's Parent
. This is the simplest and you don't need to program anything on each main (parent) form.