如何根据WPF中的进度百分比更改进度条文本颜色?

时间:2016-06-28 23:16:01

标签: c# wpf xaml progress-bar textblock

我编写了以下代码来显示进度条和显示百分比的文本。这个文本块将放在栏上。但现在字体是白色的。如果安装进度没有通过它,如何添加条件使其变黑;如果有,那么我需要将其更改为白色。我怎样才能做到这一点?请指教。

<ProgressBar Minimum="0" Maximum="100" Background="#FF1B1A1A" Value="{Binding Progress }" HorizontalAlignment="Stretch" Margin="20,182,20,121" Height="20" BorderBrush="#FF1B1A1A"  >
        <ProgressBar.Foreground>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF0A92FB"/>
                <GradientStop Color="#FF022F52" Offset="1"/>
            </LinearGradientBrush>
        </ProgressBar.Foreground>

    </ProgressBar>
    <TextBlock Name="progressLbl" Text="{Binding Progress,StringFormat={}{0}%}" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="18,182,10,121" Width="40" Height="20" Foreground="#FFE6E6E6" FontSize="12" FontFamily="Segoe UI Light"/>

1 个答案:

答案 0 :(得分:0)

绑定TextBlock's Text属性,如下所示,并将DataTriggerConverter一起用于Foreground

   <TextBlock Text="{Binding Value, ElementName=PBar1}" Margin="92,216,159,54">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Value, ElementName=PBar1, Converter={StaticResource ConvPercentageKey}}" Value="LessThan50">
                        <Setter Property="Foreground" Value="Red"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Value, ElementName=PBar1,  Converter={StaticResource ConvPercentageKey}}" Value="MoreThan50">
                        <Setter Property="Foreground" Value="Yellow"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>

转换器代码:

public class PercentageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        double v = Double.Parse(value.ToString());
        if (v < 50)
            return "LessThan50";
        else
            return "MoreThan50";
    }

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