Alkix
Alkix

Reputation: 165

How does one get a code-behind file to recognize type of a user control?

I have a custom control in my mater page that represents a menu, let's call it CustomMenu. The control code files are located in a non special directory.

I want to give each page that uses that master page the ability to access the control and, using a public property, tell the control whether or not it should render itself.

I have a public property on the control to do that, and I know I can get the control by referencing Page.Master.FindControl('IdOfControlIwant');

The problem I'm having is that I can't seem to get the control Type recognized by the compiler, so when I do find the menu control, I can't actually work with it. The only way I can get the code behind to recognize the type is to register it in the ascx file, and then add at least one control to the page, which is undesirable.

Thoughts?

Upvotes: 0

Views: 464

Answers (3)

Cognitronic
Cognitronic

Reputation: 1436

You have to combine what both Jacob and dzendras have posted. Add the MasterType directive to your content page's aspx file:

<%@ MasterType VirtualPath="~/your.master"  %>

And in the master page create a property:

public CustomMenu MyCustomMenu {get{ return myCustomMenu;}}

Where myCustomeMenu is the ID of the Usercontrol in your masterpage.

You should now be able to reference the usercontrol from a content page. So, if the CustomMenu usercontrol had a property called SelectedItem, you should be able to access it like this:

   public void Page_Load(object o, EventArgs e)
   {
       Master.MyCustomMenu.SelectedItem = 1;
   }

Upvotes: 1

dzendras
dzendras

Reputation: 4751

Make a property of your MasterPage class:

bool IsCustomMenuVisible {set{ CustomMenu.Visible = value;}}

And use it wherever you like.

Upvotes: 0

Jacob
Jacob

Reputation: 78850

Use the MasterType directive in your pages:

<%@ MasterType VirtualPath="~/your.master"  %>

That will strongly type your Master page reference, so you should be able to add properties that can be accessed by the pages.

Upvotes: 1

Related Questions