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

◇◆丶佛笑我妖孽 提交于 2019-12-20 03:09:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!