Convert string to Color in C#

后端 未结 10 1400
我寻月下人不归
我寻月下人不归 2020-11-29 07:03

I am encountering a problem which is how do I convert input strings like \"RED\" to the actual Color type Color.Red in C#. Is there a good way to do this?

10条回答
  •  悲&欢浪女
    2020-11-29 07:37

    This worked nicely for my needs ;) Hope someone can use it....

        public static Color FromName(String name)
        {
            var color_props= typeof(Colors).GetProperties();
            foreach (var c in color_props)
                if (name.Equals(c.Name, StringComparison.OrdinalIgnoreCase))
                    return (Color)c.GetValue(new Color(), null);
            return Colors.Transparent;
        }
    

提交回复
热议问题