简体   繁体   中英

asp.net - Access public class in Masterpage from child page

I'm trying to access a public class in my MasterPage code file from a child page but cannot get it working. I've tried to use the same method as accessing a public int as follows but the child page doesn't recognise any of the class items.

MasterPage.cs

private int _Section;
public int  Section
{
    get{return _Section;}
    set{_Section = value;}
}

public class HeaderPanel
{
    private bool _Visible = true;
    public bool Visible
    {
        get { return _Visible; }
        set { _Visible = value; }
    }

    private string _Theme;
    public string Theme
    {
        get { return _Theme; }
        set { _Theme = value; }
    }

    public HeaderPanel(bool Visible, string Theme)
    {
        this.Visible = Visible;
        this.Theme = Theme;
    }
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    Master.Section = 1; // This works
    Master.HeaderPanel.Visible = true; // This doesn't work
    Master.HeaderPanel.Theme = "Dark"; // This doesn't work       

}

The error message I get is:
'HeaderPanel': cannot reference a type through an expression

Master.Section = 1;

This works because Master is a property on Default and that property is an instance of MasterPage . You are simply setting the Section value on that instance.

Master.HeaderPanel.Visible = true;

This doesn't work because, while Master is still the same instance, HeaderPanel is a type and not an instance of anything. So you're trying to set Visible statically on that type.


If you meant for it to be static , make it static :

private static bool _Visible = true;
public static bool Visible
{
    get { return _Visible; }
    set { _Visible = value; }
}

And access it via the type and not the instance:

MasterPage.HeaderPanel.Visible = true;

If, on the other hand (and possibly more likely?), you did not mean for it to be static , then you need an instance of the HeaderPanel type on a MasterPage instance. So in MasterPage you'd create a property for that:

private HeaderPanel _header = new HeaderPanel();
public HeaderPanel Header
{
    get { return _header; }
    set { _header = value; }
}

Then you could access it through that property:

Master.Header.Visible = true;
private int _Section;
public int  Section
{
    get{return _Section;}
    set{_Section = value;}
}
//define your header panel as property 
public HeaderPanel Header {Get;Set;}

then you can use it as below

protected void Page_Load(object sender, EventArgs e)
{
    Master.Section = 1; // This works
    Master.Header.Visible = true; 
    Master.Header.Theme = "Dark";       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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