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

如何在WPF中创建带渐变圆弧及中部文本的静态资源适配多控件

实现WPF带渐变圆弧+中部文本的通用样式

完全可以实现这种效果,核心思路是通过ControlTemplate自定义控件外观,结合Path绘制渐变圆弧,再用ContentPresenter承载文本内容,就能把样式作为静态资源复用在Button、Label、TextBlock这类控件上。

具体实现代码

1. 定义通用静态资源样式

在Window.Resources或App.xaml中添加以下可复用的样式资源:

<Window.Resources>
    <Style x:Key="ArcWithTextStyle" TargetType="{x:Type Control}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Control}">
                    <Grid>
                        <!-- 渐变圆弧背景 -->
                        <Path StrokeThickness="15" Stretch="Uniform">
                            <Path.Stroke>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                                    <GradientStop Color="#FF4CAF50" Offset="0"/>
                                    <GradientStop Color="#FF2196F3" Offset="1"/>
                                </LinearGradientBrush>
                            </Path.Stroke>
                            <!-- 绘制270度圆弧,可调整参数修改弧度 -->
                            <Path.Data>
                                <PathGeometry>
                                    <PathFigure StartPoint="0.5,0">
                                        <ArcSegment Point="0.5,1" Size="0.5,0.5" SweepDirection="Clockwise" IsLargeArc="True"/>
                                    </PathFigure>
                                </PathGeometry>
                            </Path.Data>
                        </Path>
                        <!-- 中部文本:自动绑定控件的内容属性 -->
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"
                                          FontSize="24" FontWeight="Bold" Foreground="#333"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

2. 应用样式到目标控件

在布局中直接引用该静态资源即可:

<!-- 给Button应用样式 -->
<Button Style="{StaticResource ArcWithTextStyle}" Content="75%" Width="150" Height="150"/>

<!-- 给Label应用样式 -->
<Label Style="{StaticResource ArcWithTextStyle}" Content="80%" Width="150" Height="150"/>

<!-- 给TextBlock应用样式 -->
<TextBlock Style="{StaticResource ArcWithTextStyle}" Text="90%" Width="150" Height="150"/>

自定义调整说明

  • 圆弧弧度:修改ArcSegment的Point、IsLargeArc和SweepDirection参数可调整圆弧角度与方向,比如做180度圆弧可将Point设为1,0.5、IsLargeArc设为False。
  • 渐变效果:替换LinearGradientBrush为RadialGradientBrush可实现径向渐变,调整GradientStop的颜色和偏移值能自定义渐变色彩。
  • 文本样式:在ContentPresenter中修改FontSize、Foreground等属性,也可将这些属性绑定到控件自身属性,提升样式灵活性。
  • 圆弧粗细:调整Path的StrokeThickness参数可改变圆弧的宽度。

内容的提问来源于stack exchange,提问作者BabyHai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:22:58