我想通过更改进度颜色来制作自定义进度条。所以我写了一个代码来创建它。
我的代码:
<Style x:Key="colorizedPB" TargetType="ProgressBar">
<Setter Property="Background" Value="Red"/>
<Setter Property="BorderBrush" Value="LightGray"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ProgressBar">
<Viewbox>
<Border HorizontalAlignment="Left" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Rectangle x:Name="rect" Fill="Red" Width="0" Height="{TemplateBinding Height}">
<Rectangle.RenderTransform>
<TranslateTransform X="0" Y="0"/>
</Rectangle.RenderTransform>
</Rectangle>
</Border>
</Viewbox>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ValueChanged">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="rect"
Storyboard.TargetProperty="Width"
To="{Binding Path=Value,RelativeSource={RelativeSource TemplatedParent}}"
Duration="0:0:0.1"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Canvas Grid.Column="1" Margin="8,102,10,53">
<ProgressBar x:Name="progressBar" Style="{DynamicResource colorizedPB}" Width="200" Height="20"/>
</Canvas>
我期待这段代码能够正常运行,但事实并非如此。我认为To
的{{1}}属性存在问题。我怎样才能使它发挥作用?
答案 0 :(得分:0)
我自己找到了使用代码和XAML的解决方案。但如果有人仅使用XAML回答,我将不胜感激。
XAML样式代码:
<Style x:Key="colorizedPB" TargetType="ProgressBar">
<Setter Property="Background" Value="Red"/>
<Setter Property="BorderBrush" Value="LightGray"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ProgressBar">
<Viewbox>
<Border HorizontalAlignment="Left" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
BorderBrush="Gray" BorderThickness="1">
<Rectangle x:Name="rect" HorizontalAlignment="Left" Fill="{TemplateBinding Background}" Width="0" Height="{TemplateBinding Height}">
<Rectangle.RenderTransform>
<TranslateTransform X="0" Y="0"/>
</Rectangle.RenderTransform>
</Rectangle>
</Border>
</Viewbox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
代码背后:
void progressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
var template = progressBar.Template;
//Find the Rectangle in the ControlTemplate
var layer = (Rectangle)(template.FindName("rect", progressBar));
//Calculate the increment amount depending maxValue and Width
double artis = progressBar.Value * progressBar.Width / progressBar.Maximum;
DoubleAnimation anim = new DoubleAnimation(toValue: artis, duration: TimeSpan.FromMilliseconds(100));
layer.BeginAnimation(Rectangle.WidthProperty, anim);
}
<强>结果:强>