我意识到很多代码不能放在这里,但我要求提供一般方向或指针.
I realize that a whole lot of code cannot fit here, but I am asking for general direction or pointer.
我有一个嵌套六层的 .NET 用户控件,用于交互式小工具(从外到内):包装器、选项卡、面板、列表、行、项目.
I have .NET user controls nested six deep for an interactive gadget with (outer to inner) of : wrapper, tabs, panels, lists, rows, items.
我正在尝试从嵌套控件中获取对祖先控件的引用.
I am trying to get a reference to an ancestor control from a nested control.
具体来说,我在嵌入的曾曾孙"控件的代码背后有这段代码.它有效,但非常难看:
Specifically, I have this code in the code behind of a embedded "great great grand child" control. It works, but it is very ugly:
MyTab _myTab = this.Parent.Parent.Parent.Parent.FindControl(thisTab) as MyTab;
等于 {ASP.controls_appname_widget_mywidget_mytab_ascx}
并且是正确的.
which equals {ASP.controls_appname_widget_mywidget_mytab_ascx}
and is correct.
我意识到我可以做类似的事情Page.FindControl("MyWrapper:MyPanel:etc.....) 但也不推荐这样做,因为结构或 ID 可能会改变....
I realize that I can do something like Page.FindControl("MyWrapper:MyPanel:etc.....) but that is not recommended either, since structure or IDs can change....
有没有像样的替代品?
请记住,组件最好是无知的.您永远不希望任何控件了解层次结构中位于其自身之上的任何内容,也不希望任何控件了解层次结构中位于其自身之下的控件的仅界面知识.从长远来看,这种架构方法将为您节省很多痛苦和痛苦,并且会避免像您现在这样的情况.
Remember that components are best made ignorant. You never want any control to have any knowledge of anything above itself in the hierarchy and to have interface-only knowledge of controls below itself in the hierarchy. This architectural approach will save you much pain and suffering in the long run and will avoid situations like you are in now.
至于修复当前问题,修复它的最佳方法是在您的控件中创建一个可由父控件设置的 MyTab
成员.这不是一个完美的解决方案,因为您的控件并非完全不知道其他人,但至少您将不再需要知道如何获取 MyTab
引用 - 它会提供给您.
As for fixing the current problem the best way to fix it is to create a MyTab
member in your control that is settable by parent controls. This is not a perfect solution as your control is not totally ignorant of others but at least you will no longer have to know how to get the MyTab
reference - it will be provided to you.
因此,我将创建一个名为 ParentTab
之类的属性,并将该属性设置为等于 MyTab
引用在页面中的某处或控件内,该控件确实并且应该具有可见性MyTab
和您的控件.
So I would create a property called something like ParentTab
and set this property equal to the MyTab
reference somewhere in the page or inside a control that does and should have visibility to both MyTab
and your control.
这篇关于嵌套用户控件 - 如何最好地获得对祖先控件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!