WPF string转color ,brush

SubjectBorderTiele.BorderBrush = new 
SolidColorBrush((Color)ColorConverter.ConvertFromString("#2DE9B1"));
using MediaBrushes = System.Windows.Media.Brushes;

ColorConverter

    public class ColorHelper
    {
        /// 
        /// 色码转色刷
        /// 
        /// 
        /// 
        public static SolidColorBrush StringToBrush(string value)
        {
            // 因为色刷支持空值,所以输入为空时返回null
            if (string.IsNullOrEmpty(value)) return MediaBrushes.Transparent;
            try
            {
                // 格式验证
                var res = ColorStringFormatVerify(value);
                // 判断透明色
                if (IsTransparent(res) || string.IsNullOrEmpty(res))
                {
                    return MediaBrushes.Transparent;
                }
                // 转换色码
                var obj = new BrushConverter().ConvertFromString(res);
                if (obj == null) throw new Exception("转换失败");
                return (SolidColorBrush)obj;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// 
        /// 判断是否为透明色码
        /// 
        /// 
        /// 
        public static bool IsTransparent(string value)
        {
            var res = value.Trim(' ', '#');
            return string.Equals(res.ToUpper(), "00FFFFFF", StringComparison.OrdinalIgnoreCase);
        }

        /// 
        /// 色码格式化验证
        /// 
        /// 
        /// 
        public static string ColorStringFormatVerify(string value)
        {
            var res = value.Trim(' ', '#');
            // 判断空值
            if (string.IsNullOrEmpty(res))
            {
                throw new Exception("输入色码为空");
            }
            // 判断色码十六进制格式
            if (!Regex.IsMatch(res, @"[A-Fa-f0-9]+$"))
            {
                throw new Exception("输入色码格式错误");
            }
            // 判断色码长度
            if (res.Length != 6 && res.Length != 8)
            {
                throw new Exception("输入色码长度错误");
            }
            var length = res.Length == 6 ? 6 : 8;
            // 补齐位数
            res = res.PadRight(length, '0');
            res = res.Substring(0, length);
            res = "#" + res;
            return res;
        }
    }

你可能感兴趣的:(经验总结,C#,wpf,c#)