TextBlock文本值设置TextBlock的Foregrou

TextBlock文本值设置TextBlock的Foregrou

本文介绍了如何通过TextBlock文本值设置TextBlock的Foreground属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过TextBlock文本值设置TextBlock的前台属性?例如:文本值为Mike,前景属性为Black,值为Tim,属性值为绿色,依此类推.我用google搜索,但找不到任何解决方案.

it’s possible set the foreground property of a TextBlock by TextBlock text value?For example: Text value is Mike, foreground property is Black, value is Tim, property value is green, etc. I search with google, but I don’t find any solution.

推荐答案

如果您希望灵活地执行一些聪明的事情,例如将文本动态映射为颜色等,则可以使用Converter类.我假设文本设置为绑定到某些东西,您可以在前景中绑定到相同的东西,但可以通过自定义转换器:

If you want the flexibility to do something smart, such as dynamically map texts to colors and so on, you could use a Converter class. I am assuming the text is set to bind to something, you could bind to the same something in Foreground but through a custom converter:

<TextBlock Text="{Binding Path=Foo}"
           Foreground="{Binding Path=Foo, Converter={StaticResource myConverter}" />

您的转换器将被定义如下:

Your converter would be defined something like this:

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语句.

Obviously, instead of the simple switch statement you could have smarter logic to handle new values and such.

这篇关于如何通过TextBlock文本值设置TextBlock的Foreground属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:06