开发者

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 TextBlo开发者_StackOverflow中文版ck 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.


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.


Based on the number of voted comments, I am revising the answer from @danut-enachioiu to implement the solution using Brushes, instead of Colors so that the value returned will match the type of the WPF Element Property.

TextBlock.Foreground is 'System.Windows.Media.Brushes'

Here is the revised code...

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 Brushes.Red;
            case "John":
                return Brushes.Blue;
            default:
                return Brushes.Black;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜