SiteMap menu with icons

While binding a Menu (or TreeView: everything in this article applies to TreeView as well) to a SiteMapDataSource is very easy, it can prove challenging to find how to extend the site map with custom properties and use these extended properties in a Menu. This sample shows how to add icons in a sitemap-driven menu.

SiteMap allows the addition of custom attributes to your site map nodes. If you're using the XML site map provider, it's as simple as this:

<siteMapNode url="default.aspx" title="Home"  description="The home page" imageUrl="home.gif">

Here, imageUrl is a custom property, not defined by the SiteMap infrastructure by default.

The first idea that comes to mind to use these custom attributes is to just replace the automatic bindings you get from binding a Menu to SiteMapDataSource with "manual" bindings. This works very well with XmlDataSource because it is implemented so that the nodes implement ICustomTypeDescriptor, so any XML attribute is exposed as a property on the node as far as reflection is concerned. This is a very powerful feature of .NET reflection that gives it some of the qualities of dynamic languages. Unfortunately, SiteMapDataSource does not implement this, nor does Menu know how to query custom site map attributes. This is an oversight and we may add that support in future releases.

An easy (although not declarative) way out of this problem is to hook the OnMenuItemDataBound event and to set the custom properties from there:

public void OnItemBound(object sender, MenuEventArgs args) {
    args.Item.ImageUrl = ((SiteMapNode)args.Item.DataItem)["imageUrl"];

I hope this helps.

Here's a link to the full source code for this sample:


Comments have been disabled for this content.