ASP.NET2.0MenuControl:setstaticitemselectedwhen 

來源:互聯網
上載者:User

Menu控制項是將當前的url與其自身items中的url做比較,將相同的item置於選中狀態。但是通常我們只是顯示一級靜態item,這樣動態item處於選中狀態時我們是不能直接看到的,只能在開啟靜態menuitem的下拉式清單才能看到。而且有時我們根本就不顯示動態items。而我們通常的需求是:只要是在sitemap檔案裡被組織在一個樹型結構裡的頁面,我都希望在進入它時,menu控制項的對應根節點處於選中狀態,這樣再配合selectedstyle,我們很容易將網站各個功能模組用不同的樣式區分開。

很可惜menu控制項預設不支援這個功能,下個版本據說會加進去。目前我們可以通過控制MenuItemDataBound事件來實現,如下:

        if (e.Item.Selected && e.Item.Parent != null)
        {
            e.Item.Parent.Selected = true;
        }

這麼做的前提時你要顯示出所有的dynamic items,也就是說MaximumDynamicDisplayLevels屬性要>0。但是有時並不想顯示dynamic items,只需在做完上面的判斷後,動態移除子items:

        if (e.Item.Parent != null)
        {
            e.Item.Parent.ChildItems.Remove(e.Item);
        }

以下時完整代碼:

    protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
    {
        if (e.Item.Selected && e.Item.Parent != null)
        {
            e.Item.Parent.Selected = true;
        }

        if (e.Item.Parent != null)
        {
            e.Item.Parent.ChildItems.Remove(e.Item);
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.