简体   繁体   English

MasterPages 继承另一个 MasterPage

[英]MasterPages Inherit another MasterPage

I am working on a website that has many MasterPages and one of them inherits from another master page and I am trying to add a control to the parent masterpage like this我正在一个有许多 MasterPages 的网站上工作,其中一个从另一个母版页继承,我正在尝试像这样向父母版页添加一个控件

myMasterPage.Page.Controls.Add(new LiteralControl(theSuperStoreString.ToString()));

But I get the following error但我收到以下错误

The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

How can i do this?我怎样才能做到这一点?

Thank you谢谢

First of all you should never add any control to your parent control.首先,您永远不应该向父控件添加任何控件。 It violates separation of concerns principle, breaks integrity and is the first sign of bad design (and troubles in the project).它违反了关注点分离原则,破坏了完整性,并且是糟糕设计(以及项目中的麻烦)的第一个迹象。

If you have to modify Controls of your parent or another control use event, state property or interface to delegate this request to the object which is really responsible for it (parent MasterPage in that case).如果您必须修改父控件或其他控件使用事件的控件,请使用 state 属性或接口将此请求委托给真正负责它的 object(在这种情况下为父 MasterPage)。

Regarding to your question place a control in your parent MasterPage and show it only when someone request for it.关于您的问题,请在您的父 MasterPage 中放置一个控件,并仅在有人请求时显示它。

I think you are trying to add the control too late in the cycle, try the preinit event我认为您试图在周期中添加控件为时已晚,请尝试 preinit 事件

added as I read your comment在我阅读您的评论时添加

here is a link to the lifecycle这是生命周期的链接

http://msdn.microsoft.com/en-us/library/ms178472.aspx http://msdn.microsoft.com/en-us/library/ms178472.aspx

so essentially what we are saying is you need to overrid ethe preinit event and add/create new controls there rather than the later events (where it seems you are currently trying to add)所以本质上我们要说的是你需要覆盖预初始化事件并在那里添加/创建新控件而不是后来的事件(你目前似乎正在尝试添加的地方)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM