繁体   English   中英

嵌套母版页和继承

[英]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.

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