问题
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.
回答1:
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.
回答2:
you have a model view (implementing INotifyPropertyChanged) that has the Text as a property and the foreground color as a property, have the textblock bind those two properties to the model view. the color property can depend on the text property.
来源:https://stackoverflow.com/questions/4099837/wpf-how-do-i-set-the-foreground-property-of-a-textblock-by-textblock-text-value