Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 296
Rani Avatar asked Dec 21 '22 01:12

Rani


1 Answers

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();
    }
}
like image 114
Clemens Avatar answered Dec 27 '22 10:12

Clemens