Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the Foreground property of a TextBlock by TextBlock text value?

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.

like image 932
Joe Avatar asked Dec 28 '22 05:12

Joe


1 Answers

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;
    }
}

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

like image 77
Danut Enachioiu Avatar answered Apr 27 '23 14:04

Danut Enachioiu