With WPF, it’s pretty easy to create a converter to display the color of a text depending on an Enum value. Here is a simple example with IValueConverter.

Let’s start with the View:

<Window x:Class="TextBlockConverter.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:prism="http://prismlibrary.com/" xmlns:converters="clr-namespace:TextBlockConverter.Converters" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="200" Width="200"> <Window.Resources> <converters:StatusToColorConverter x:Key="StatusToColorConverter"/> </Window.Resources> <Grid> <StackPanel Margin="65"> <TextBlock Text="{Binding StatusOk}" Foreground="{Binding StatusOk, Converter={StaticResource StatusToColorConverter}}"/> <TextBlock Text="{Binding StatusNOk}" Foreground="{Binding StatusNOk, Converter={StaticResource StatusToColorConverter}}"/> </StackPanel> </Grid> </Window>
Code language: HTML, XML (xml)

As you can see, we use a converter to select the correct color. Here is the code for this converter:

using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; using TextBlockConverter.Models; namespace TextBlockConverter.Converters { public class StatusToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is StatusEnum && value != null) { StatusEnum status = (StatusEnum)value; var color = new SolidColorBrush(Colors.White); switch (status) { case StatusEnum.Ok: color = new SolidColorBrush(Colors.Green); break; case StatusEnum.NOk: color = new SolidColorBrush(Colors.Red); break; default: color = new SolidColorBrush(Colors.White); break; } return color; } return Binding.DoNothing; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
Code language: C# (cs)

The color will be based on the Status Enum:

namespace TextBlockConverter.Models { public enum StatusEnum { Ok = 1, NOk = 2 } }
Code language: C# (cs)

And of course our simple ViewModel:

using Prism.Mvvm; using TextBlockConverter.Models; namespace TextBlockConverter.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "TextBlock Enum Converter"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } private StatusEnum _statusOk; public StatusEnum StatusOk { get { return _statusOk; } set { SetProperty(ref _statusOk, value); } } private StatusEnum _statusNOk; public StatusEnum StatusNOk { get { return _statusNOk; } set { SetProperty(ref _statusNOk, value); } } public MainWindowViewModel() { StatusOk = StatusEnum.Ok; StatusNOk = StatusEnum.NOk; } } }
Code language: C# (cs)

Happy coding 🙂