Apply CSS to single instance of Custom user Contro

2019-08-30 01:13发布

问题:

Ok I created simple user control that look like this

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PlaceHolderCMS.ascx.cs" Inherits="Controls_PlaceHolderCMS" %>

<div id="contentPlaceholder" runat="server" class="contentPlaceholderStyle">
</div>

I am using it like this

<div class="mainField" runat="server">             
  <cms:PlaceHolder ID="PlaceHolderCMS1" runat="server" class="PH1" />
  <cms:PlaceHolder ID="PlaceHolderCMS2" runat="server" />
</div>

But my problem is CSS, I can edit styles that is asociated with entire control, like this

.contentPlaceholderStyle
{
    border-style :dashed;
    background-color:transparent;
    border-width:1px; 
    padding: 10px, 10px, 0px, 0px;  
    margin:15px;
    height:100px;
}

But when i try to style single instance of user control nothing happens. I tried this from stylesheet, like this

.PH1
{    
    height:100px;
}

and from C#, like this protected void Page_Load(object sender, EventArgs e)

{

PlaceHolderCMS1.Attributes["style"] = "width=" + width + "%; height:" + height + "px;" ;

}

So my question is how can I put style attributes for instances of my Custom Control? I want to have general styles for entire control, and override them for particular instances if needed.

Thank you in advance....

回答1:

Your problem is that UserControl doesn't render any tag for himself. Since that it's nothing to apply your class on. So it's abolutely on you to provide some custom CssClass property for your control and assign this to some container that holds all your control children.

Control's markup:

<div class='<%= CssClass %>' >
    <div id="contentPlaceholder" runat="server" class="contentPlaceholderStyle">
    </div>
</div>

Control's code-behind:

[CssClassProperty]
public string CssClass
{
    get { return (string)(ViewState["CssClass"] ?? ""); }
    set { ViewState["CssClass"] = value; }
}


回答2:

The simplest way to do this would likely be to have multiple classes on the control. During initialization of the control you could add the default class to any defined by your code, ie:

this.CssClass += "contentPlaceholderStyle";

in your initialization.



回答3:

You seem to be applying styles to the user control itself, but what you want to do is apply styles to the outermost div in your control. That shouldn't work unless you override the properties of the user control to reference the properties of the outermost div.