You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin中如何自定义包含文本内容的进度条

XAML 自定义进度条实现代码

以下是完全匹配参考样式的WPF进度条实现,支持圆角效果、进度百分比显示、自定义配色:

首先需要先定义转换器,用来把进度值换算为进度条填充的宽度:

public class ProgressToWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double progress = (double)value;
        ProgressBar bar = (ProgressBar)((FrameworkElement)parameter).TemplatedParent;
        return progress / bar.Maximum * bar.ActualWidth;
    }

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

然后在XAML资源中添加进度条样式:

<Window.Resources>
    <local:ProgressToWidthConverter x:Key="ProgressToWidthConverter"/>
    <Style x:Key="CustomProgressBar" TargetType="ProgressBar">
        <Setter Property="Height" Value="12"/>
        <Setter Property="Minimum" Value="0"/>
        <Setter Property="Maximum" Value="100"/>
        <Setter Property="Background" Value="#F0F0F0"/>
        <Setter Property="Foreground" Value="#2563EB"/>
        <Setter Property="FontSize" Value="12"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ProgressBar">
                    <Grid>
                        <!-- 进度百分比文本 -->
                        <TextBlock Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, StringFormat={}{0}%}"
                                   HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0 -24 0 0"
                                   Foreground="#333333"/>
                        <!-- 进度条背景轨道 -->
                        <Border CornerRadius="6" Background="{TemplateBinding Background}"/>
                        <!-- 进度填充区域 -->
                        <Border CornerRadius="6" HorizontalAlignment="Left"
                                Background="{TemplateBinding Foreground}"
                                Width="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource ProgressToWidthConverter}, ConverterParameter={Binding RelativeSource={RelativeSource Self}}}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

调用方式非常简单,直接给ProgressBar指定样式、绑定进度值即可:

<ProgressBar Style="{StaticResource CustomProgressBar}" Value="72" Width="320" HorizontalAlignment="Left"/>
  • 如需调整圆角大小,修改Border的CornerRadius属性即可,建议值为进度条高度的1/2实现完全圆角效果
  • 可自行修改Background、Foreground属性调整轨道和进度条的填充色,支持渐变画笔
  • 不需要百分比显示的话,直接删掉模板中的TextBlock节点即可

内容的提问来源于stack exchange,提问作者Chim Di Tru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:45:03