从字符串中获取 SolidColorBrush [英] Getting SolidColorBrush from a string
问题描述
我正在尝试使用字符串(类似于红色")在后端设置文本块的前景
I'm trying to set the foreground of a textblock on the backend using a string ( something like "Red")
我已经试过了:
ColorText.Foreground = new BrushConverter().ConvertFromString(colors[color2].ToString());
但是,它似乎无法识别 BrushConvert()
.我已经包含了 System.Windows.Media
但仍然找不到.
However, it doesn't seem to be recognizing BrushConvert()
. I've included System.Windows.Media
but it still can't be found.
还有其他方法可以做到这一点吗?
Is there another way to go about doing this?
推荐答案
BrushConverter
在 windows phone 中不可用.您可以构建一个颜色字典,然后使用辅助方法将您想要的颜色传递给 SolidColorBrush
ctor.
BrushConverter
isn't available in windows phone. You could build up a dictionary of colors then pass the color you want to SolidColorBrush
ctor with a helper method.
public static class ColorsHelper {
private static readonly Dictionary<string, Color> dict =
typeof(Colors).GetProperties(BindingFlags.Public | BindingFlags.Static)
.Where(prop => prop.PropertyType == typeof(Color))
.ToDictionary(prop => prop.Name, prop => (Color)prop.GetValue(null, null));
public static Color FromName(string name) {
return dict[name];
}
}
ColorText.Foreground = new SolidColorBrush(ColorsHelper.FromName("Red"));
确保上面的字典使用了System.Windows.Media.Color
结构体和System.Windows.Media.Colors
类.我相信周围有一些 Color
类型,因此如有必要,请输入整个命名空间或重命名.
Make sure the above dictionary uses System.Windows.Media.Color
struct and System.Windows.Media.Colors
class. I believe there are a few Color
types around so type in the whole namespace if necessary or rename it.
这篇关于从字符串中获取 SolidColorBrush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!