Thursday, December 13, 2007

MasterPage tips

It pays to look around at what other developers are doing. Today I was reading SimpleTalk articles (see Phil Factor) and found the Master Pages Tips and Tricks: Specifically, I do not need to cast the Master page to be able to use my custom properties.
Fortunately, a strongly-typed solution is available that doesn't involve casting the Master property to the base class of the master page in order to access its members (keep in mind that any server controls defined in the master page won't be accessible even after a cast is performed, because they're marked as protected by default).
In cases where a control defined in a master page needs to be exposed to one or more content pages in a strongly-typed manner, a public property with a get block can be added into the master page class as shown in Figure 2. The get block returns a Label control instance named lblHeader.

A content page can reference members defined in the custom master page class by adding the MasterType directive immediately under the Page directive:

<%@ MasterType VirtualPath="~/Templates/WebsiteMasterPage.master" %>
This causes the ASP.NET compiler to use the custom master page class for the type of the Page class's Master property as opposed to the default MasterPage class

No comments: