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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With