EPiServer:PageList with SelectedItemTemplate

This is a quick guide how to extend EPiServer:PageList with a SelectedItemTemplate. This is a good start if you want to try to extend it with a SeparatorTemplate or something more spectacular.

1. Create a class
I.e. PageList.cs, a recommendation is to follow EPiServers namespace, so in this case I would create my class in Antecknat.Web.WebControls.
This class should inherit EPiServer.Web.WebControls.PageList

namespace Antecknat.Web.WebControls
{
public class PageList : EPiServer.Web.WebControls.PageList
{

2. Create the SelectedItemTemplate
This is done by the following code:

private ITemplate _selectedItemTemplate;
[TemplateContainer(typeof(PageTemplateContainer)), Browsable(false), PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate SelectedItemTemplate
{
get
{
return this._selectedItemTemplate;
}
set
{
this._selectedItemTemplate = value;
}
}

3. Modify CreateChildControls()
With Reflector (the best program ever made?) we can reuse the way controls are added to the regular PageList. We need to change the current method so that the SelectedItemTemplate is used when is supposed to.
In this case I want the current page, the parent page, the parents parents page and so on to count as selected. So we’ll make a PageReferenceCollection containing these pages.

// Find pages that should be marked as Selected
PageReferenceCollection prcActivePages = new PageReferenceCollection();
PageReference prCurrentLevel = CurrentPage.PageLink;
while (prCurrentLevel != null && prCurrentLevel != PageReference.EmptyReference)
{
prcActivePages.Add(prCurrentLevel);
prCurrentLevel = EPiServer.DataFactory.Instance.GetPage(prCurrentLevel).ParentLink;
}

And where the regular ItemTemplate is added, we change the code from:

ItemTemplate.InstantiateIn(control2);

to:

if (prcActivePages.Contains(pages[i].PageLink)) // Add to SelectedItemTemplate if in Selected collection
SelectedItemTemplate.InstantiateIn(control2);
else // Add to normal ItemTemplate
ItemTemplate.InstantiateIn(control2);

4. Change web.config
This is not a mandatory step, but if you always want to be able to use your fresh PageList from any aspx or ascx in the project, add teh following line in <system.web><pages><controls>

<add tagPrefix="Antecknat" namespace="Antecknat.Web.WebControls" assembly="Antecknat"/>

5. Use your PageList
Now you can use your PageList in your .aspx and .ascx files.
Just type

<Antecknat:PageList ID="PageList1" runat="server>
<HeaderTemplate><ul></HeaderTemplate>
<FooterTemplate></ul></FooterTemplate>
<ItemTemplate><li><%# Container.CurrentPage.PageName %></li>
<SelectedItemTemplate><li class="selected"><%# Container.CurrentPage.PageName %></li>
</Antecknat:PageList>

And then add a PageDataCollection from code behind and databind it.

Download sourcecode
PageList.zip