场景:2 个用户控件(foo.ascx 和 fum.ascx)
foo 有一个非常想从 fum 访问属性的方法。他们生活在同一页面上,但我找不到一种非常简单的方法来完成这种交流。
有任何想法吗?
OnMyPropertyValueChanged
在 fum.ascx 中添加一个事件。有几种方法可以处理这个问题,但最好的解决方案是尽可能解耦。
最解耦的方法是递归的 findControl 方法,它遍历控件对象模型,直到找到所需的控件并返回引用。
private Control findControl(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = findControl(c, id);
if (t != null)
{
return t;
}
}
return null;
}
这是另一种很简洁的方法,虽然我不知道我是否会使用它。(有点伪代码):
public FunkyUserControl : UserControl
{
private List<UserControl> subscribedControls;
public List<UserControl> Subscribers
{
get { return subscribedControls;}
}
public void SubscribeTo(UserControl control)
{
subscribedControls.Add(control);
}
}
从 FunkyUserControl 继承您的两个用户控件,然后在您的主页类中,您可以执行以下操作:
webControl1.SubscribeTo(webControl2);
webControl2.SubscribeTo(webControl1);
现在每个控件都可以自省其订阅者集合以找到另一个控件。
将事件添加到与窗体挂钩的 UserControl。
您可以使用FindControl
on引用其他用户控件Foo's Parent
。这是最简单的,您不需要在每个主(父)表单上编写任何内容。
'From within foo...call this code<br>
Dim objParent As Object<br>
Dim lngPropID As Long<br>
objParent = Me.Parent.FindControl("fum")<br>
lngPropID= objParent.PropID 'public property PropID on fum<br>
最简单的解决方案是 fum 将一个值存储在 HttpContext.Current.Items[] 中,foo 以后可以在其中读取它。
一个更强大的选项是给 foo 一个属性,该页面可以使用对 fum 的引用来填充该属性。
一个事件是更多的工作,但在架构上更好。