ASP.NET Menu Control - Keeping parent item selected

前端 未结 2 1383
日久生厌
日久生厌 2021-01-26 08:14

I have two ASP.NET Menu controls on a page.

One in my header (tabs) for top level pages, e.g. ~/Default.aspx

And one in my sidebar for sub pages, e

相关标签:
2条回答
  • 2021-01-26 09:13

    My menu isn't databound so MenuItemDataBound is never fired. Below is my solution to highlight the parent menu item when there are child items and when there are not:

    Add a StaticSelectedStyle-xxx to the Menu, like StaticSelectedStyle-BackColor="#757588"

    Call this method on Page_Load:

    protected void SetSelectedMenuItem()
            {
                string pageViewed = this.Page.AppRelativeVirtualPath;
    
                foreach (MenuItem item in Menu.Items)
                {
                    if (item.ChildItems.Count > 0)
                    {
                        if (pageViewed == item.Value)
                        {
                            item.Selected = true;
                        }
                        else
                        {
                            foreach (MenuItem childItem in item.ChildItems)
                            {
                                if (pageViewed == childItem.Value)
                                {
                                    if (childItem.Parent != null)
                                    {
                                        childItem.Parent.Selected = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (pageViewed == item.Value)
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
    
    0 讨论(0)
  • 2021-01-26 09:21

    Figured it out with help of related question:

    Set item.selected in ASP.NET Menu Control

    protected void Page_Load(object sender, EventArgs e)
    {
        MenuControl.MenuItemDataBound += new MenuEventHandler(MenuControl_MenuItemDataBound);
    }
    
    void MenuControl_MenuItemDataBound(object sender, MenuEventArgs e)
    {
        if (SiteMap.CurrentNode != null)
        {
            if (SiteMap.CurrentNode.ParentNode.Url == e.Item.NavigateUrl)
            {
                e.Item.Selected = true;
            }
        }
     }
    
    0 讨论(0)
提交回复
热议问题