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

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

问题描述

我意识到很多代码都不能容纳在这里,但是我要的是一般的方向或指针.

我有一个.NET用户控件嵌套了六个深度,用于一个交互式小工具,其中(从外到内)有:包装器,选项卡,面板,列表,行,项.

我试图从嵌套控件中获取对祖先控件的引用.

具体来说,我在嵌入式伟大的曾孙"控件的后面的代码中有此代码.它可以工作,但是非常丑陋:

MyTab _myTab = this.Parent.Parent.Parent.Parent.FindControl(thisTab) as MyTab;

等于{ASP.controls_appname_widget_mywidget_mytab_ascx}并且正确.

我意识到我可以做类似的事情 Page.FindControl("MyWrapper:MyPanel:etc ...),但也不建议这样做,因为结构或ID可以更改....

有不错的选择吗?

解决方案

请记住,最好使组件变得无知.您永远都不希望任何控件对层次结构中位于其上方的任何东西有任何了解,而对层次结构中位于其自身之下的控件仅具有接口的了解.从长远来看,这种架构方法可以为您节省很多痛苦和痛苦,并且可以避免像您现在这样的情况.

关于解决当前问题的最佳方法是在控件中创建可由父控件设置的MyTab成员.这不是一个完美的解决方案,因为您的控件并不完全不了解其他控件,但至少您将不再需要知道如何获取MyTab引用-它会提供给您.

因此,我将创建一个名为ParentTab之类的属性,并将此属性设置为与页面或控件中的MyTab引用相等,该控件应该同时对MyTab和您的控件具有可见性. /p>

I realize that a whole lot of code cannot fit here, but I am asking for general direction or pointer.

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;

which equals {ASP.controls_appname_widget_mywidget_mytab_ascx} and is correct.

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....

Is there a decent alternative?

解决方案

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.

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.

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天全站免登陆