如何根据当前值当前值的范围更改进度条前景色

Ran*_*ani 4 wpf colors progress-bar

我已经检查了下面的问题,但我没有完全得到,因为我是WPF的新手. 有没有办法通过绑定到视图模型属性来更改WPF进度条的颜色

如果您有任何样品,请提供给我.

Cle*_*ens 10

您可以在进度条的绑定Foreground属性,它的Value使用属性值转换器,从转换doubleBrush,像显示在下面的例子.请注意,为了测试,ProgressBar的Value属性也被绑定,特别Value是Slider控件的属性.

<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>
Run Code Online (Sandbox Code Playgroud)

绑定值转换器可能如下所示:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)