嵌套用户控件 - 如何最好地获取对祖先控件的引用 [英] Nested User Controls - how to best get a reference to an ancestor control

查看:19
本文介绍了嵌套用户控件 - 如何最好地获取对祖先控件的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这里放不下很多代码,但我要求提供大致的方向或指针.

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.

这篇关于嵌套用户控件 - 如何最好地获取对祖先控件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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