从代码更改CSS类 [英] Change CSS classes from code

查看:91
本文介绍了从代码更改CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在后面的代码中设置CssClass很容易,但这会覆盖现有类.

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

我需要将某些元素设置为ReadOnly = true;,我想将样式用作视觉提示,以确保该项目无法更改...很容易:

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";

但是有时我 还需要将相同的元素更改为ReadOnly = false;,这意味着我将需要删除设置的CSS类,而无需删除可能已分配的任何其他样式

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?

推荐答案

我采用了AnthonyWJones的原始代码并对其进行了修改,以使其在任何情况下均能正常工作:

I've taken AnthonyWJones original code and amended it so that it works no matter what scenario:

static class WebControlsExtensions
    {
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Add(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }

        public static void RemoveCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Remove(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }
    }

    static class StringExtensions
    {
        public static string ToDelimitedString(this IEnumerable<string> list, string delimiter)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string item in list)
            {
                if (sb.Length > 0)
                    sb.Append(delimiter);

                sb.Append(item);
            }

            return sb.ToString();
        }
    }

这篇关于从代码更改CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆