ASP.NET:如何在codebehind上设置menuitem的cssclass

问题描述 投票:1回答:1

如何从代码隐藏为ASP.NET Menu控件的每个menuitem设置不同的cssclass?所有这些菜单都在第2级。所以像这样的东西是行不通的,因为level2上的所有菜单项最终会有相同的cssclass(level2class),我希望能够为每个菜单项设置不同的样式:

<LevelMenuItemStyles>
    <asp:MenuItemStyle CssClass="level1class"/>
    <asp:MenuItemStyle CssClass="level2class"/>    
</LevelMenuItemStyles>

所以我想做这样的事情:

MenuItem myMenu = new MenuItem();
myMenu.Text = "MyMenu";
Menu1.Items.Add(myMenu); //Menu1 is the name of the asp.net Menu control

foreach (DataRow row in myDataTable.Rows)
 {
    MenuItem myItem = new MenuItem();
    string myItemName = row["myItemName"].ToString();
    myItem.Text = myItemName; 

    //HERE COMES THE PROBLEM. I'M NOT ABLE TO DEFINE A DIFFERENT CSSCLASS FOR EACH MENUITEM.
    if (myItemName == "x1")
    { 
          myItem.CssClass = "x1class";  //THIS DOES NOT WORK AS MENUITEM DOES NOT HAVE CSSCLASS PROPERTY
    }
   else if (myItemName == "x2")
   {
         myItem.CssClass = "x2class";  //THIS DOES NOT WORK AS MENUITEM DOES NOT HAVE CSSCLASS PROPERTY
   }

   myMenu.ChildItems.Add(myItem);
}

另一个可能的替代方案可能会工作,但也是如此:

if (myItemName == "x1")
 { 
     MenuItemStyle ms = new MenuItemStyle();
     ms.CssClass = "x1class";
     //HOW DO I SET ms OBJECT TO THE myItem OBJECT?
}
else if (myItemName == "x2")
{
     MenuItemStyle ms = new MenuItemStyle();
     ms.CssClass = "x2class";
     //HOW DO I SET ms OBJECT TO THE myItem OBJECT?
}

谢谢

asp.net css menu styles menuitem
1个回答
0
投票

但是,如果你真的想要一个CSS类,你可以使用Attributes.Add方法...像这样的myItem.Attributes.Add( "class", "pretty" );

© www.soinside.com 2019 - 2024. All rights reserved.