无法从另一个调用 ASP.NET 用户控件 [英] Unable to call an ASP.NET user control from another

查看:29
本文介绍了无法从另一个调用 ASP.NET 用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从另一个用户控件访问用户控件的公共属性.但是,我无法在另一个用户控件中访问一个用户控件.即使在使用命名空间ASP"之后,我也只能看到对当前用户控件的引用.

但是,在页面中,我可以使用 ASP 命名空间引用所有用户控件.

是我遗漏了什么还是必须那样做?

更新:这是确切的场景 -
我有两个用户控件 A 和 B.现在它们都用于 Page Default.aspx.控件 A 上有一个公共属性,其中包含在 A 中单击的控件的名称.我希望访问控件 B 中的此属性以做出一些决定.根据您的建议,我理解通过容器页面的 FindControl 方法到达控件,但是当我无法在 B 中获取控件 A 的引用时,如何将其强制转换为控件 A 以获取属性值?

感谢大家的帮助!

解决方案

一个用户控件不应该知道另一个用户控件(当然,任何包含的子控件除外).如果 ControlABC 引用了 ControlXYZ,那么您永远不能在任何页面上使用 ControlABC,除非该页面也有 ControlXYZ 的实例 - 这会严重损害您重用 ControlABC 的能力.

解决此问题的一种方法是使用事件连接"两个控件之间的连接.这样,ControlABC 就不会对 ControlXYZ 有很强的依赖性——它可以很容易地重复使用,即使在没有 ControlXYZ 的页面上也是如此.页面可以管理两个控件之间的连接,将ControlXYZ上的委托添加到ControlABC上的事件中,这样两个控件就可以通信了.

可能还有其他技术可以让您的控件相互交互而不引入强依赖项,与事件/委托相比,这可能有利有弊.其他 SO 成员会指出它们的,我敢肯定.

I wish to access a user control's public property from another user control. But, I am not able to access one user control within another. Even after using the namespace 'ASP', I am only able to see the reference to the current user control.

However, in a page I am able to refer to all the user controls with the ASP namespace.

Am I missing something or it needs to be that way?

Update: Here the exact scenario -
I have two user controls A and B. Now both of them are being used on a Page Default.aspx. There is a public proprty on control A which holds the name of the control clicked within A. I wish to access this property in control B to make some decisions. With the suggestions gioven by you, I understand reaching to the control by FindControl method of the container page, but how do I cast it to control A to fetch the property value when I cannot get the reference of the control A in B?

Thanks for the help guys!

解决方案

One user control should not know about another user control (with the exception of any contained child controls, of course). If ControlABC referenced ControlXYZ, then you could never use ControlABC on any page, unless that page also had an instance of ControlXYZ - it would significantly hurt your ability to re-use ControlABC.

One way to address this is to use events to "wire up" a connection between the two controls. That way, ControlABC doesn't have a strong dependency on ControlXYZ - it can be re-used easily, even on pages where there is no ControlXYZ. The page can manage the connection between the two controls, adding delegates on ControlXYZ to the events on ControlABC, so the two controls can communicate.

There are likely other techniques for allowing your controls to interact with each other without introducing strong dependencies, which may have pros and cons, compared to events/delegates. Other SO members will point them out, I'm sure.

这篇关于无法从另一个调用 ASP.NET 用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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