问题描述:

So I have 2 master pages and one user control which is used on almost every page. Page may have one of 2 master pages and both master pages have one property common. It is a list variable that I need access. How do I know which master page is being used and then access it?

I am trying

MasterPage mp = (MasterPage)this.Page.Master;

but when I debug, I don't see the list property. mp.List doesn't work. Any idea on how to get this property?

Thanks in advance

网友答案:

Consider using a simple interface to make this easy.

public interface IHasProperty 
{
   List<string> MyVariable {get;set;}
}

public partial class MasterPage1 : (other stuff), IHasProperty
{
   List<string> MyVariable {get;set;}
}

public partial class MasterPage2 : (other stuff), IHasProperty
{
   List<string> MyVariable {get;set;}
}

then from the user control, you can access this by using something like this.

var myPropPage = Page.Master as IHasProperty;
if (myPropPage == null)
{
   //this property isnt on the page.
   return;
}

myPropPage.MyVariable.Add("new Value");// or whatever you needed to do with it. 
网友答案:

Add a strongly typed reference to the master page on your aspx as so:

<%@ MasterType VirtualPath="~/Site.Master" %> 

Then in the code behind you can do this.Master without having to cast and the list should be accessible.

相关阅读:
Top