Change CSS classes from code

2019-01-11 11:48发布

It's easy to set CssClass in the code-behind, but this runs the risk of overwriting existing classes.

I need to set certain elements to ReadOnly = true; and I'd like to apply a style as a visual cue that the item cannot be altered...easy enough:

.CssClass += " ReadOnlyStyle";

But at times I will also need to change the same element to ReadOnly = false; which means that I will need to remove the CSS class that I set without removing any other styles that I might have assigned.

What's the best way to do this?

7条回答
▲ chillily
2楼-- · 2019-01-11 12:43

This version checks to make sure the given class isn't already added before adding it.

public static void CssAddClass(this WebControl control, string className)
{
    var classNames = control.CssClass.Split
        (new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    if (classNames.Contains(className))
    {
        return;
    }

    control.CssClass = string.Concat
        (classNames.Select(name => name + " ").ToArray()) + className;
}

public static void CssRemoveClass(this WebControl control, string className)
{
    var classNames = from name in control.CssClass.
                         Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                     where name != className
                     select name + " ";


    control.CssClass = string.Concat(classNames.ToArray()).TrimEnd();
}
查看更多
登录 后发表回答