[SOLVED] How to change the progressbar foreground color based on its value depending on the range the current value is currently in

Issue

i have already checked the below question but i didnt get completely as i am new to WPF.
Is there a way to change the color of a WPF progress bar via binding to a view model property

If you have any sample please provide me.

Solution

You could bind the ProgressBar’s Foreground property to its Value property by using a value converter which converts from double to Brush, like shown in the example below. Note that for testing the ProgressBar’s Value property is also bound, in particular to the Value property of a Slider control.

<Window.Resources>
    <local:ProgressForegroundConverter x:Key="ProgressForegroundConverter"/>
</Window.Resources>
<StackPanel>
    <ProgressBar Margin="10"
                 Value="{Binding ElementName=progress, Path=Value}"
                 Foreground="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Value, Converter={StaticResource ProgressForegroundConverter}}"/>
    <Slider Name="progress" Margin="10" Minimum="0" Maximum="100"/>
</StackPanel>

The binding value converter could look like this:

public class ProgressForegroundConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double progress = (double)value;
        Brush foreground = Brushes.Green;

        if (progress >= 90d)
        {
            foreground = Brushes.Red;
        }
        else if (progress >= 60d)
        {
            foreground = Brushes.Yellow;
        }

        return foreground;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Answered By – Clemens

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *