[英]Nested Master Pages and Inheritance
我創建了一個嵌套的母版頁。 父母版頁A繼承自System.Web.UI.MasterPage。 子母版頁B繼承自A。
然后,我創建了一個使用母版頁B的Web內容頁C,並從System.Web.UI.Page繼承。
CI可以從Web內容頁面訪問兩個母版頁中的變量和方法。 但是,問題出在訪問父母版頁變量和方法。
問題是正在引發NullReferenceException。 變量和方法尚未初始化。
有什么可能的解決方案?
public partial class ParentMasterPage : System.Web.UI.MasterPage
{
internal Button btn_Parent
{
get { return btn; }
}
}
public partial class ChildMasterPage : ParentMasterPage
{
internal Button btn_Child
{
get { return btn; }
}
}
public partial class WebContentPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
Button tempA = Master.btn_Child; //WORKS
Button tempB = Master.btn_Parent; //NULL REFERENCE EXCEPTION
}
}
嵌套母版頁不會繼承其父母版頁的類型。 相反,它自身構成 ,使得NestedMasterType.Master
屬性是父母版頁的實例。 NestedMasterType
類型仍然從System.Web.UI.MasterPage
繼承。
所以這是正確的:
public partial class ChildMasterPage : System.Web.UI.MasterPage
這是錯誤的:
public partial class ChildMasterPage : ParentMasterPage
然后,您將以如下方式訪問(子級)頁面的(父級)母版(使用子級母版):
Button tempA = ((ChildMasterPage)this.Master).btn_Child;
Button tempB = ((ParentMasterPage)this.Master.Master).btn_Parent;
注意:此答案假定您的意思是ChildMasterPage
是一個嵌套的母版頁,它使用類似於以下內容的Master
指令:
<%@ Master MasterPageFile="~/ParentMasterPage.Master" Inherits="ChildMasterPage"...
頁面僅具有對其直接母版及其變量的引用,您必須將對象圖向上遍歷到主母版頁,即
var parentMaster = (ParentMasterPage)Page.Master.Master;
parentMaster.SomeProperty = ...;
另外,您可以通過在ChildMasterPage
實現相同的屬性來縮小兩者之間的差距,即
internal Button btn_Parent
{
get { return ((ParentMasterPage)Master).btn_Parent; }
}
這意味着您當前擁有的代碼可以使用,但是,這有點違背了擁有主頁的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.