如何从属性背后的代码中获取style属性的值?

时间:2016-07-03 16:17:47

标签: c# css asp.net .net visual-studio-2013

在我的.aspx中我有这个:

 <style type="text/css">
       .item .item_background .item_general_info .button_wrapper .add_button {

           background-color: /* MyProp from code behind */
       }

   </style>

关于背后的代码:

public String MyProp 
{
  get {return DB.GetColor();}
}

如何从后面的代码中动态设置背景颜色的值?

由于

2 个答案:

答案 0 :(得分:1)

如果这是一个aspx,你可以尝试在类上定义该成员作为受保护的成员:

protected string _myServerColor;

然后在页面加载时分配该道具:

protected void Page_Load(object sender, EventArgs e) { _myServerColor = "#FFF"; // assign this to your db color }

然后,只要您的样式标记位于同一页面内,您就可以:

<style type="text/css">
       .item .item_background .item_general_info .button_wrapper .add_button {

           background-color: "<%= _myServerColor %>";
       }

   </style>

最干净的方法是制作此控件runat="server",以便您可以直接从后端分配属性。

此致

答案 1 :(得分:0)

您可以通过以下方式从代码隐藏向CSS样式类添加样式属性:

Style style1 = new Style();
style1.BackColor = Color.Orange; // Insert the desired color here
Header.StyleSheet.CreateStyleRule(style1, null, ".item .item_background .item_general_info .button_wrapper .add_button");

为了实现这一点,页面的head部分必须具有runat="server"属性:

<head runat="server">
    <style type="text/css">
        .item .item_background .item_general_info .button_wrapper .add_button 
        {
            ...
        }
    </style>
    ...
</head>
相关问题