Thursday, September 20, 2012

One possible solution to the problem of the StaticSelectedStyle not working

If you run into a situation in which the StaticSelectedStyle property of your asp:Menu control simply isn't working, I have a solution that worked for me and might just work for you.  In my particular case, I have a Menu web control located on the Master Page of my web app and I'm using the following code to define my menu:

...
<asp:Menu ID="mnuMain" CssClass="NavigationMenu"  
    staticdisplaylevels="2" DynamicHorizontalOffset="1"
    staticsubmenuindent="1px" MaximumDynamicDisplayLevels="4"
    orientation="Horizontal" runat="server">
    <StaticHoverStyle CssClass="NavigationMenu_StaticHoverStyle" />
    <StaticMenuItemStyle CssClass="NavigationMenu_ItemStyle" />
    <StaticSelectedStyle CssClass="NavigationMenu_StaticSelectedStyle" />
    <Items>
        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Review My Groups" />
...

The root cause of my problem with the style of the selected item not being set properly was, ultimately, due to the fact that I wasn't updating the Selected property of the menu item that represents the current page being displayed.  To resolve the issue, I simply added the following code to the PageLoad event of my Master Page, the location where my Menu control resides, to set the Selected property of the menu:
protected void Page_Load(object sender, EventArgs e)
{
    string currentPage = Page.AppRelativeVirtualPath;
    foreach (MenuItem item in mnuMain.Items)
    {
        if (item.NavigateUrl == currentPage)
        {
            item.Selected = true;
        }
    }
}

This code basically tells the Menu which item has been selected and will enable the StaticSelectedStyle property to be applied to the selected menu item.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.