首页 > 解决方案 > 如何动态设置 ASCX 文件中的背景颜色?

问题描述

我有一个名为的 ASCX 文件AegHero,其中有一个 WebPart 的标记。我还有一个BackgroundColor包含类名的属性,该类名对应于具有特定背景颜色的类。

我认为我的问题是我没有正确定义后面代码中的值。我正在使用下拉菜单让用户选择一种颜色:

在此处输入图像描述

这是我的 AegHero.ascx:

<asp:PlaceHolder runat="server">
    <div id="mainHeroContainer" class="fullWidth-hero-container <%= BackgroundColor %>">
        <div class="fullWidth-hero-container-inner">
            <h2 class="fillWidth-hero-title"><%=Title %></h2>
            <p class="fillWidth-hero-subtilte"><%=SubTitle %></p>

            <% if (ShowButton)
                {%>
            <a class="btn button" href="<%= ButtonUrl %>"><%= ButtonLabel %></a>
            <%} %>
        </div>
    </div>
</asp:PlaceHolder>

这是我背后的代码:

public partial class AegHero : GenericWebPart
    {
        protected string Title => Html("Title", string.Empty);
        protected string SubTitle => Html("subTitle", string.Empty);
        protected bool ShowButton => GetBooleanValue("ShowButton", false);
        protected string ButtonUrl => StringProperty("ButtonUrl", string.Empty);
        protected string ButtonLabel => StringProperty("ButtonLabel", string.Empty);
        protected string BackgroundColor
        {
            get { return StringProperty("BackgroundColor", string.Empty); }
            set { BackgroundColor = value; }
        }

        public override void OnContentLoaded()
        {
            base.OnContentLoaded();

            if (BackgroundColor.CompareTo("#002147") == 0)
            {
                BackgroundColor = "perussian-backGround";
            }
            else if (BackgroundColor.CompareTo("#0077c2") == 0)
            {
                BackgroundColor = "lochmara-backGround";
            }
            else if (BackgroundColor.CompareTo("#858e99") == 0)
            {
                BackgroundColor = "gray-backGround";
            }
        }
    }
}

这是我的CSS类:

.gray-backGround {
  background: #858e99;
}

.lochmara-backGround {
  background: #0077c2;
}

.perussian-backGround {
  background: #002147;
}

我正在尝试<%= BackgroundColor %>根据我收到的十六进制值设置;但是,当我查看我的 chrome 检查器时,类并没有改变。如何从 backgroundColor 属性中正确获取值并将其设置为<div>

铬检查员:

在此处输入图像描述

标签: c#asp.netkenticoascx

解决方案


您可能想了解如何创建/开发自定义 Web 部件以开始使用。我这样说是因为您的公共属性没有从 UI 中的 web 部件检索存储的值。这是一个标准的属性示例:

public string BackgroundColor
{
    get
    {
        return DataHelper.GetNotEmpty(GetValue("BackgroundColor"), string.Empty);
    }
    set
    {
        SetValue("BackgroundColor", value);
    }
}

GetValue("BackgroundColor")方法采用您在 Kentico UI 中的 webpart 属性上创建的列的字符串名称,并检索存储在给定页面/模板的数据库中的值。这允许编辑器从前端 Kentico UI 中选择或输入颜色,并允许您在代码中使用它。

阅读有关文档的更多信息,它应该会让您朝着正确的方向前进。


推荐阅读