Search code examples
c#wpfmvvmtextblock

Color TextBlock depending on enum value


I'm working on WPF with a MvvM model.

I have a view containing Texblocks. It display information about ID (from a document and from a database) :

<GroupBox Grid.Row="1" Grid.Column="0" Header="ID Informations">
    <StackPanel Orientation="Vertical">
        <TextBlock Text="DataBase surname: "/>
        <TextBlock Text="{Binding Model.Db_SURNAME}" FontWeight="Bold"/>
        <TextBlock Text="Document surname: "/>
        <TextBlock Text="{Binding Model.Dc_SURNAME}" FontWeight="Bold"/>
        <TextBlock Text="DataBase forename: "/>
        <TextBlock Text="{Binding Model.Db_FORENAME}" FontWeight="Bold"/>
        <TextBlock Text="Document forename: "/>
        <TextBlock Text="{Binding Model.Dc_FORENAME}" FontWeight="Bold"/>
    </StackPanel>
</GroupBox>

I have an enum containing an error code :

[Flags]
public enum errorID
{
    OK = 1<<0,
    SURNAME_DIFF = 1 << 1,
    FORENAME_DIFF = 1 << 2
}

And my model is wrote like this :

private String _db_SURNAME;
public String Db_SURNAME
{
    get { return _db_SURNAME; }
    set { SetProperty(ref _db_SURNAME, value); }
}
[...]

private errorID _errorID;
public errorID ErrorID
{
    get { return _errorID; }
    set { SetProperty(ref _errorID, value); }
}

I want that both of my textblocks displaying Model.Db_SURNAME and Model.Dc_SURNAME are colored in red when ErrorID.HasFlag(errorID.SURNAME_DIFF ). And also for Forname.

How can I do ?


Solution

  • Use a converter that converts your enum to a color like following:

    public class ErrorIdColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(!(value is errorID))
                 throw new ArgumentException("value not of type errorID");
            if(!(parameteris errorID))
                 throw new ArgumentException("parameter not of type errorID");
    
            errorID error = (errorID)value;
            errorID flag = (errorID)parameter;
    
            if (error.HasFlag(flag))
            {
                return Brushes.Red;
            }
            ...
    
            return Brushes.Black;
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
       ....
    }
    

    }

    Then you can bind the Foreground Color to your enum using the converter:

    <TextBlock Text="{Binding Model.Db_SURNAME}" FontWeight="Bold" Foreground={Binding Model.errorId, Converter={StaticRessource errorIDColorConverter}, ConverterParameter={StaticRessource errorID.SURNAME_DIFF}}/>