开发者

Ad Hoc Styles in WebControl

开发者 https://www.devze.com 2023-03-16 01:20 出处:网络
I\'m creating a WebControl that is used in several of my ASP.NET pages. In one instance, I\'d like to add some ad hoc style attributes such as Width and Float.

I'm creating a WebControl that is used in several of my ASP.NET pages. In one instance, I'd like to add some ad hoc style attributes such as Width and Float.

Since I can't anticipate which attributes will be needed in the future, I'd like the markup using the control to be able to add any random style. I've got the control so it supports standard styles like Color, Width, etc., but not Float.

Is there any way to allow such attributes to be specified in the markup and have them propagate through to the rendered control unchanged? I'd like not to have to create my own custom Float property and any other possible style that might be needed.

I tried just adding style="..开发者_JS百科." in the markup, but this is simply stripped out and does not appear anywhere in the rendered control.


My previous answer pertains to User Controls, my mistake!

For a WebControl you can over ride the AddAttributesToRender method.

The following seems to work quite well:

    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public string style
    {
        get
        {
            String s = (String)ViewState["style"];
            return ((s == null) ? String.Empty : s);
        }

        set
        {
            ViewState["style"] = value;
        }
    }

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {            

        base.AddAttributesToRender(writer);
        if(!string.IsNullOrEmpty(style))
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Style, style);
        }

    }

EDIT: Changed public property to "style" to take advantage of intellisence.


I would add a CssClass property to your WebControl. This would allow any page that uses your control to supply its own look and feel.


It may not be what you are looking for but if you having a surrounding element you could apply the styles as a string as per the following:

.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="HubbInvestor.WebUserControl1" %>
<div style="<%=AdHocStyle%>">
    Some Text:
    <asp:Button ID="Button1" runat="server" Text="A Button" />
</div>

.ascx.cs

public partial class WebUserControl1 : System.Web.UI.UserControl
{
    private string adHocStyle = string.Empty;

    public string AdHocStyle
    {
        get { return adHocStyle; }
        set { adHocStyle = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

of course you don't get any nice intellisense completion on the styles

0

精彩评论

暂无评论...
验证码 换一张
取 消