Thursday, June 18, 2009

Extending System.Web.UI.WebControls.Style to handle all style attributes. E.g. text-align

When using the Page.Header.StyleSheet.CreateStyleRule method I ran into a limitation of the System.Web.UI.WebControls.Style class. I could only set a small subset of the available CSS attributes. In particular, I couldn't set text-align using the WebControls.Style class.

By overriding the Style.FillStyleAttributes method I can add additional CSS attributes to the CssStyleCollection.

class ExtendedStyle : Style
{
    private Dictionary<System.Web.UI.HtmlTextWriterStyle, string> extendedAttributes;

    public string TextAlign
    {
        get
        {
            return GetAttribute(System.Web.UI.HtmlTextWriterStyle.TextAlign);
        }
        set
        {
            SetAttribute(System.Web.UI.HtmlTextWriterStyle.TextAlign, value);
        }
    }

    private string GetAttribute(System.Web.UI.HtmlTextWriterStyle attribute)
    {
        return (extendedAttributes.ContainsKey(attribute))?extendedAttributes[attribute]:null;
    }

    private void SetAttribute(System.Web.UI.HtmlTextWriterStyle attribute, string value)
    {
        if (value == null)
        {
            extendedAttributes.Remove(attribute);
        }
        else
        {
            extendedAttributes[attribute] = value;
        }
    }

    public ExtendedStyle()
    {
        extendedAttributes = new Dictionary();
    }

    protected override void FillStyleAttributes(System.Web.UI.CssStyleCollection attributes, System.Web.UI.IUrlResolutionService urlResolver)
    {
        base.FillStyleAttributes(attributes, urlResolver);

        foreach (System.Web.UI.HtmlTextWriterStyle attribute in this.extendedAttributes.Keys)
        {
            attributes[attribute] = extendedAttributes[attribute];
        }
    }
}

Which allows me to do the following:

Page.Header.StyleSheet.CreateStyleRule(new ExtendedStyle() { TextAlign = "right" }, this, ".foobar");