C# 从代码更改 CSS 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/445967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:39:36  来源:igfitidea点击:

Change CSS classes from code

c#cssasp.netwebforms

提问by nailitdown

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

CssClass在代码隐藏中设置很容易,但这会冒覆盖现有类的风险。

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:

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

.CssClass += " ReadOnlyStyle";

But at times I will alsoneed 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.

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

What's the best way to do this?

做到这一点的最佳方法是什么?

采纳答案by John_

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

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

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();
        }
    }

回答by Al W

Can you make your own custom classes? Derive from the ASP.NET Button and add a propert for Read only. Somewhere...probably in the OnPreRender, you can check the new property and set (or not set) the CSSClass property accordingly.

您可以制作自己的自定义类吗?派生自 ASP.NET 按钮并添加只读属性。某处...可能在 OnPreRender 中,您可以检查新属性并相应地设置(或不设置)CSSClass 属性。

回答by AnthonyWJones

In C# 3 you can add some extension methods.

在 C# 3 中,您可以添加一些扩展方法。

 static class WebControlsExtensions
 {
     public static void AddCssClass (this WebControl control, string cssClass)
     {
         control.CssClass += " " + cssClass;
     }
     public static void RemoveCssClass (this WebControl control, string cssClass)
     {
         control.CssClass = control.CssClass.replace(" " + cssClass, "");
     }
 }

Usage:-

用法:-

ctl.AddCssClass("ReadOnly");
ctl.RemoveCssClass("ReadOnly");

Note the RemoveCssClass is designed to remove only those classes added by AddCssClass and has the limitation that where 2 additional class names is added the shortest name should not match exactly the start of the longest name. E.g., If you added "test" and "test2" you can't remove test without corrupting the CssClass. This could be improved with RegEx by I expect the above to be adequate for your needs.

请注意,RemoveCssClass 旨在仅删除由 AddCssClass 添加的那些类,并且具有限制,即在添加 2 个附加类名称的情况下,最短名称不应与最长名称的开头完全匹配。例如,如果您添加了“test”和“test2”,则无法在不破坏 CssClass 的情况下删除测试。这可以通过 RegEx 改进,因为我希望上述内容足以满足您的需求。

Note if you don't have C#3 then remove the thiskeyword from the first parameter and use the static methods in the conventional manner.

请注意,如果您没有 C#3,this则从第一个参数中删除关键字并以常规方式使用静态方法。

回答by core

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();
}

回答by Hewins

I made a version for pre-C#3:

我为 pre-C#3 制作了一个版本:

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

                if (!classes.Contains(cssClass)) {
                    classes.Add(cssClass);
                }

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

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

                bool removed = true;
                while (removed) {
                    removed = classes.Remove(cssClass);
                }

                control.CssClass = StringExtensions.ToDelimitedString(classes, " ");
            }
    }
    static class StringExtensions {
        public static string ToDelimitedString(List<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();
        }
    }

Used like:

像这样使用:

WebControlsExtensions.AddCssClass(ctl, "classname");
WebControlsExtensions.RemoveCssClass(ctl, "classname");

This one will only add a class if it's not already there. It will also remove all instances of a class (if, for some reason, there are multiple in there)

如果它不存在,这个只会添加一个类。它还将删除一个类的所有实例(如果由于某种原因,那里有多个实例)

回答by Evgeni Nabokov

Pure .NET 2.0 (No extensions! No LINQ! No RegEx! No unnecessary WebControl class!). These methods are quite general to be used not for CSS classes only.

纯 .NET 2.0(没有扩展!没有 LINQ!没有 RegEx!没有不必要的 WebControl 类!)。这些方法非常通用,不仅仅用于 CSS 类。

public static string AddCssClass(string classContainer, string className)
    {
        if (string.IsNullOrEmpty(classContainer)) return className ?? string.Empty;
        if (string.IsNullOrEmpty(className)) return classContainer;

        var classNames = classContainer.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (Array.Exists(classNames, delegate(string s) { return s.Equals(className); })) return classContainer;

        return classContainer + " " + className;
    }

    public static string RemoveCssClass(string classContainer, string className)
    {
        if (string.IsNullOrEmpty(classContainer)) return className ?? string.Empty;
        if (string.IsNullOrEmpty(className)) return classContainer;

        var classNames = classContainer.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        int index = Array.FindIndex(classNames, delegate(string s) { return s.Equals(className); });
        if (index >= 0)
        {
            return string.Join(" ", classNames, 0, index) +
                (   index + 1 < classNames.Length ?
                    " " + string.Join(" ", classNames, index + 1, classNames.Length - index - 1)
                    :
                    string.Empty    );
        }

        return classContainer;
    }

    public static string ToggleCssClass(string classContainer, string className)
    {
        if (string.IsNullOrEmpty(classContainer)) return className ?? string.Empty;
        if (string.IsNullOrEmpty(className)) return classContainer;

        var classNames = classContainer.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        if (Array.Exists(classNames, delegate(string s) { return s.Equals(className); })) return RemoveCssClass(classContainer, className);

        return classContainer + " " + className;
    }

回答by Bruce Allen

Related... if you just want to toggle a Class based upon a condition...

相关...如果您只想根据条件切换类...

bool disable = true;      // this will vary (true/false) based on UI state

string newClass = disable ? "BtnGray" : "BtnPink";

string currentClass = disable ? "BtnPink" : "BtnGray";

myButton.CssClass = myButton.CssClass.Replace( currentClass, newClass );