AvaloniaUI ProgressBar 基本样式和用法
在AvaloniaUI中使用ProgressBar控件时,可以通过以下代码定义基本样式和绑定数据:
csharp
<ProgressBar
Minimum="0"
Maximum="100"
Value="{Binding ProgressValue}"
Width="200"
Height="20"/>
对应的ViewModel需要包含进度值属性:
csharp
private double _progressValue;
public double ProgressValue
{
get => _progressValue;
set => this.RaiseAndSetIfChanged(ref _progressValue, value);
}
自定义进度条样式
通过Avalonia的样式系统可以修改进度条外观:
xml
<Style Selector="ProgressBar">
<Setter Property="Background" Value="#E0E0E0"/>
<Setter Property="Foreground" Value="#0078D7"/>
<Setter Property="Height" Value="10"/>
<Setter Property="CornerRadius" Value="5"/>
</Style>
<Style Selector="ProgressBar:disabled">
<Setter Property="Opacity" Value="0.6"/>
</Style>
动画效果实现
为进度变化添加平滑动画:
xml
<Style Selector="ProgressBar">
<Setter Property="Template">
<ControlTemplate>
<Border Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}">
<Rectangle Name="PART_Track"
Fill="{TemplateBinding Foreground}"
CornerRadius="{TemplateBinding CornerRadius}"
Width="{TemplateBinding Value, Converter={StaticResource PercentageConverter}}"/>
</Border>
</ControlTemplate>
</Setter>
<Style.Animations>
<Animation Duration="0:0:0.3" Easing="Linear">
<KeyFrame Cue="0%">
<Setter Property="Opacity" Value="0.5"/>
</KeyFrame>
<KeyFrame Cue="100%">
<Setter Property="Opacity" Value="1"/>
</KeyFrame>
</Animation>
</Style.Animations>
</Style>
不确定状态进度条
处理未确定进度的场景:
xml
<ProgressBar IsIndeterminate="True"
Width="200"
Height="8">
<ProgressBar.Styles>
<Style Selector="ProgressBar:indeterminate">
<Setter Property="Foreground" Value="#FF5722"/>
</Style>
</ProgressBar.Styles>
</ProgressBar>
进度文本显示
在进度条上叠加文本显示百分比:
xml
<Grid Width="200" Height="24">
<ProgressBar Value="{Binding ProgressValue}"
Minimum="0"
Maximum="100"/>
<TextBlock Text="{Binding ProgressValue, StringFormat={}{0}%}"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
垂直进度条实现
通过旋转实现垂直方向进度条:
xml
<ProgressBar Width="20"
Height="100"
Rotation="-90"
HorizontalAlignment="Left"
Value="{Binding ProgressValue}"/>
注意事项
- 确保
Value属性始终在Minimum和Maximum范围内,否则会引发异常 - 使用数据绑定时实现
INotifyPropertyChanged接口确保UI更新 - 复杂样式建议放在资源字典中复用
- 不确定模式(
IsIndeterminate)与确定模式互斥 - 高精度进度建议使用
double类型而非int