0

I've been trying to find a way to style the asp.menu control for a while. Many of the examples online were not helpful as the attributes for setting styles does not work (ie StaticMenuItemStyle-CssClass="SOMECLASS"). So I was hoping there was a way to do it programmatically? Please help.

protected void Menu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (e.Item.NavigateUrl.Trim() == _currentUrl.Trim())
    {
        // Something like this
        e.Item.CssClass = "SOMECLASS";
    }
}

EDIT I've done a work around for my Site Navigation. If there is a way to use ASP.NET Menu Style Attributes let me know!

protected void Menu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    MenuItem menuitem = (MenuItem)e.Item;
    if (menuitem.NavigateUrl.Trim() == _currentUrl.Trim())
    {
        if (menuitem.Depth == 1)
        {
            menuitem.Text = "<span class=\"active" + menuitem.Depth + " selectedlevel1\">" + menuitem.Text + "</span>";
        }
        else
        {
            menuitem.Text = "<span class=\"active" + menuitem.Depth + " selectedlevel2\">" + menuitem.Text + "</span>";
        }
        while (menuitem.Parent != null)
        {
            menuitem = menuitem.Parent;
            String title = menuitem.Text;
            title = title.Replace("<span>", "");
            title = title.Replace("</span>", "");
            menuitem.Text = "<span class=\"active" + menuitem.Depth + "\">" + title + "</span>";
        }
    }
    else
    {
        menuitem.Text = "<span>" + menuitem.Text + "</span>";
    }
}
Anna
  • 239
  • 1
  • 7
  • 21

1 Answers1

0

You should mark the item as selected

e.Item.Selected = true;

And set DynamicSelectedStyle-CssClass (and / or StaticSelectedStyle-CssClass, honestly not sure which one applies on your case) with "SOMECLASS"

EDIT

It seems that there is a problem Menu control and selected class. This other question presents a workaround for your scenario that might help you.

Community
  • 1
  • 1
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • @Anna: selected is not rendered but selected css class should be set. – Claudio Redi Jun 26 '12 at 16:37
  • That's the thing, the selected class is not set. – Anna Jun 26 '12 at 17:24
  • e.Item.Selected = true has been added to the MenuItemDataBound – Anna Jun 26 '12 at 18:55
  • @Anna: I don't have any code with asp menu at hand to check this. I found this similiar question that might help you. It seems that indeed there is some kind of problem with selected class http://stackoverflow.com/questions/2655377/how-to-style-an-asp-net-menu-with-css – Claudio Redi Jun 26 '12 at 19:55