问题
I asked a related question on this yesterday, and was told what not to do, but not what I should do.
I've got a master page that I'll call "TheMaster". I've got 2 sub master pages "Sub1" and "Sub2". They both have a Masterpage directive of "TheMaster". Web Forms have a Masterpage directive of "Sub1" or "Sub2". These aren't the real names.
In "TheMaster", I figure out what page the user is on, find out where in the Web.sitemap they are, and using that, I have the Web.sitemap node and the parent and the parent's parent, if they all exist. I use this to build navigation dynamically and highlight the current page.
Now, our designers have several places this navigation appears. Top nav, sub nav, teritiary nav on the left, and a "breadcrumb" style showing home -> parentparentnode -> parentnode -> currentpage
I can NOT define all of this in "TheMaster" due to layout constraints.
So, in "TheMaster", I find their current node, and save that as a public property of "TheMaster" (along with several other pieces of info.
In Sub1, even though it is using "TheMaster" as it's masterpage, it does not appear to be able to find my public properties from "TheMaster".
Any ideas on how I can get this info to be available all the way through this house of cards?
I've tried
Page.Master.myProp (nope)
Parent.myProp (nope)
I can't think of anyything else to get this to work. "TheMaster" has basically no knowledge of "Sub1", so I can't set a property on Sub1 and have it go down the tree, and the nodes down the tree are apparently oblivious to their parents...???
回答1:
Cast Parent or Page.Master to your actual MasterPage class.
((MyMaster)Page.Master).myProp // found!
回答2:
Casting gets you there, but it isn't so clean nor maintainable in the long run. I've done very, very complex versions of this using a series of interfaces to abstract things. See this blog post for a simplified version with one layer. The trick to adding more layers is just adding some more interfaces and abstract classes as appropriate.
来源:https://stackoverflow.com/questions/952771/masterpage-submasterpage-web-form-getting-properties-of-masterpage-in-su