Menu - StaticSelectedStyle is not working properly

Selected Styles and Master Pages

When an <asp:Menu> control appears on a master page, the "selected" styles (StaticSelectedStyle) do not work as expected. That is, menu styling to indicate a clicked link is not automatically applied. In the above example, selected items are displayed with a white background and bold characters. However, special scripting is needed to produce this effect. The reason is that selected styles are applied after the page loads the newly selected content page. Since the new content page also causes reloading of the master page, prior reference to the selected menu item is no longer available. The new page "doesn't remember" which menu item was clicked on the previous page.

A method to style a menu item to correspond with a loaded page is shown below. This Page_Load subprogram appears on the previous master page. It gets the path of the current page, extracts the .aspx file name from the path, and programmatically selects the menu item with a matching NavigateUrl property. Once this item is selected, all StaticSelectedStyle properties are automatically applied to the item.

 

 

Sub Page_Load

  '-- Get page name from relative path
  Dim ThisPage As String = Page.AppRelativeVirtualPath
  Dim SlashPos As Integer = InStrRev(ThisPage,"/")
  Dim PageName As String = Right(ThisPage, Len(ThisPage) - SlashPos)

  '-- Select menu item with matching NavigateUrl property
  Dim ParentMenu As MenuItem
  Dim ChildMenu As MenuItem
  For Each ParentMenu in NavigationMenu.Items
    If ParentMenu.NavigateUrl = PageName Then
      ParentMenu.Selected = True
    Else
      For Each ChildMenu in ParentMenu.ChildItems
        If ChildMenu.NavigateUrl = PageName Then
          ChildMenu.Selected = True
        End If
      Next
    End If
  Next

End Sub

 

protected void Page_Load(object sender, EventArgs e)
{
    string thisPage = Page.AppRelativeVirtualPath;


    MenuItem childMenu;

    foreach (MenuItem parentMenu in Menu1.Items)
    {
        if (parentMenu.NavigateUrl == thisPage)
        {
            parentMenu.Selected = true;
        }

    }
}

Ref:

http://msconline.maconstate.edu/tutorials/ASPNET2/ASPNET10/aspnet10-02.aspx

posted @ 2008-05-29 06:46  Vincent Yang  阅读(1205)  评论(1编辑  收藏  举报