可以通过 TextBlock 文本值设置 TextBlock 的前景属性吗?
例如:文本值为Mike,前景属性为Black,值为Tim,属性值为green等。我用google搜索,但没有找到任何解决方案。
如果您希望灵活地做一些聪明的事情,例如动态地将文本映射到颜色等,您可以使用 Converter 类。我假设文本设置为绑定到某些内容,您可以通过自定义转换器绑定到前台中的相同内容:
<TextBlock Text="{Binding Path=Foo}"
Foreground="{Binding Path=Foo, Converter={StaticResource myConverter}" />
您的转换器将定义如下:
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = (string)value;
switch (text)
{
case "Mike":
return Colors.Red;
case "John":
return Colors.Blue;
default:
return Colors.Black;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
显然,您可以使用更智能的逻辑来处理新值等,而不是简单的 switch 语句。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)