首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF SolidColorBrush困境

WPF SolidColorBrush困境
EN

Stack Overflow用户
提问于 2009-06-01 21:06:38
回答 2查看 4.1K关注 0票数 8

有人知道如何在WPF中将表示颜色的字符串转换为SolidColorBrush吗?

例如:

代码语言:javascript
复制
string colorRed = "Red";
SolidColorBrush fromStringToColor = new SolidColorBrush(colorRed);

这在某种程度上是我想要实现的。有什么想法吗?

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-06-01 21:23:03

您必须将字符串转换为System.Windows.Media.Color,您可以使用静态ColorConverter.ConvertFromString方法完成此操作:

代码语言:javascript
复制
string colorRed = "Red";
Color c = (Color)ColorConverter.ConvertFromString(colorRed);
SolidColorBrush fromStringToColor = new SolidColorBrush(c);
票数 21
EN

Stack Overflow用户

发布于 2012-10-30 16:49:42

代码语言:javascript
复制
        private SolidColorBrush GetColorFromString(string color)
        {
            if (color.StartsWith("#"))
            {
                if (color.Length == 9)
                    return new SolidColorBrush(
                        Color.FromArgb(
                            Convert.ToByte(color.Substring(1, 2), 16),
                            Convert.ToByte(color.Substring(3, 2), 16),
                            Convert.ToByte(color.Substring(5, 2), 16),
                            Convert.ToByte(color.Substring(7, 2), 16)
                        )
                    );
                else
                    if (color.Length == 7)
                        return new SolidColorBrush(
                            Color.FromArgb(
                                0xff,
                                Convert.ToByte(color.Substring(1, 2), 16),
                                Convert.ToByte(color.Substring(3, 2), 16),
                                Convert.ToByte(color.Substring(5, 2), 16)

                            )
                        );
            }
            else
            {
                Type colorType = (typeof(System.Windows.Media.Colors));
                if (colorType.GetProperty(color) != null)
                {
                    object o = colorType.InvokeMember(color,
                    System.Reflection.BindingFlags.GetProperty, null, null, null); if (o != null)
                    {
                        return new SolidColorBrush((Color)o);
                    }
                }
            }
            return new SolidColorBrush(Colors.Transparent);

        }

SolidColorBrush c1 = GetColorFromString("Red");
SolidColorBrush c2 = GetColorFromString("#ffff0000");
SolidColorBrush c3 = GetColorFromString("#ff0000");
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/936786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档