WPF实现圆形进度条的示例代码

 更新时间:2023年01月04日 09:35:12   作者:驚鏵  
这篇文章主要为大家详细介绍了WPF如何实现圆形的进度条,文中的示例代码讲解详细,对我们学习或工作有一定帮助,感兴趣的小伙伴可以了解一下

WPF 实现圆形进度条

  • 框架使用.NET40
  • Visual Studio 2019;
  • CircularProgressBar 继承 ProgressBar,在 XAML 中创建两个 Path 的 Data 设置 ArcSegment 修改第二个控件的 Point ,设置 StartPoint = new Point(Size.Width, 0) 设置起点。
  • 创建依赖属性 Angle 作为修改 ArcSegment 的 Point 作为进度条的圆的闭合。
  • 当进度条 ValueChanged 时创建 DoubleAnimation 动画,修改 Angle 。

示例代码

1) CircularProgressBar.xaml 代码如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:controls="clr-namespace:WPFDevelopers.Controls"
                    xmlns:convert="clr-namespace:WPFDevelopers.Converts">
    
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Basic/ControlBasic.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    <convert:AngleToPointConverter x:Key="prConverter"/>
    <convert:AngleToIsLargeConverter x:Key="isLargeConverter"/>
    <Style TargetType="{x:Type controls:CircularProgressBar}" BasedOn="{StaticResource ControlBasicStyle}">
        <Setter Property="Maximum" Value="100"/>
        <Setter Property="StrokeThickness" Value="10"/>
        <Setter Property="Foreground" Value="{DynamicResource InfoSolidColorBrush}"/>
        <Setter Property="Background" Value="{DynamicResource PrimaryNormalSolidColorBrush}"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <!--<Setter Property="Width" Value="100"/>
        <Setter Property="Height" Value="100"/>-->
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:CircularProgressBar}">
                    <controls:SmallPanel Width="{Binding ElementName=PART_Path,Path=ActualWidth}" 
                            Height="{Binding ElementName=PART_Path,Path=ActualHeight}"
                            HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                            VerticalAlignment="{TemplateBinding VerticalAlignment}">
                        <Canvas>
                            <Path Stroke="{TemplateBinding BorderBrush}"
                              StrokeThickness="{TemplateBinding BrushStrokeThickness}"
                                  x:Name="PART_Path">
                                <Path.Data>
                                    <PathGeometry>
                                        <PathFigure x:Name="PART_PathFigure">
                                            <ArcSegment SweepDirection="Clockwise"
                                                    IsLargeArc="True"
                                                    x:Name="PART_ArcSegment">
                                            </ArcSegment>
                                        </PathFigure>
                                    </PathGeometry>
                                </Path.Data>
                            </Path>
                            <Path Stroke="{TemplateBinding Background}" 
                              StrokeThickness="{TemplateBinding StrokeThickness}">
                                <Path.Data>
                                    <PathGeometry>
                                        <PathFigure x:Name="PART_PathFigureAngle">
                                            <ArcSegment SweepDirection="Clockwise"
                                                    IsLargeArc="{Binding Path=Angle, Converter={StaticResource isLargeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=ProgressBar}}"
                                                    x:Name="PART_ArcSegmentAngle">
                                                <ArcSegment.Point>
                                                    <MultiBinding Converter="{StaticResource prConverter}">
                                                        <Binding Path="Angle" RelativeSource="{RelativeSource FindAncestor, AncestorType=ProgressBar}"/>
                                                        <Binding Path="Size" RelativeSource="{RelativeSource FindAncestor, AncestorType=ProgressBar}"/>
                                                    </MultiBinding>
                                                </ArcSegment.Point>
                                            </ArcSegment>
                                        </PathFigure>
                                    </PathGeometry>
                                </Path.Data>
                            </Path>
                        </Canvas>
                        <TextBlock Foreground="{TemplateBinding Foreground}" 
                                   Text="{Binding Path=Value, StringFormat={}{0}%, 
                                RelativeSource={RelativeSource TemplatedParent}}"
                                   FontSize="{TemplateBinding FontSize}"
                                   VerticalAlignment="Center"
                                   HorizontalAlignment="Center"
                                   x:Name="PART_TextBlock"/>
                    </controls:SmallPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

2) CircularProgressBar.xaml.cs 代码如下:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace WPFDevelopers.Controls
{
    [TemplatePart(Name = ArcSegmentTemplateName, Type = typeof(ArcSegment))]
    [TemplatePart(Name = ArcSegmentAngleTemplateName, Type = typeof(ArcSegment))]
    [TemplatePart(Name = PathFigureTemplateName, Type = typeof(PathFigure))]
    [TemplatePart(Name = PathFigureAngleTemplateName, Type = typeof(PathFigure))]
    [TemplatePart(Name = TextBlockTemplateName, Type = typeof(TextBlock))]
    public class CircularProgressBar : ProgressBar
    {
        private const string ArcSegmentTemplateName = "PART_ArcSegment";
        private const string ArcSegmentAngleTemplateName = "PART_ArcSegmentAngle";
        private const string PathFigureTemplateName = "PART_PathFigure";
        private const string PathFigureAngleTemplateName = "PART_PathFigureAngle";
        private const string TextBlockTemplateName = "PART_TextBlock";
        private ArcSegment _arcSegment, _arcSegmentAngle;
        private PathFigure _pathFigure, _pathFigureAngle;
        private TextBlock _textBlock;


        public static readonly DependencyProperty SizeProperty =
           DependencyProperty.Register("Size", typeof(Size), typeof(CircularProgressBar),
               new PropertyMetadata(new Size(50,50)));
        public static readonly DependencyProperty AngleProperty =
            DependencyProperty.Register("Angle", typeof(double), typeof(CircularProgressBar),
                new PropertyMetadata(0.0));

        public static readonly DependencyProperty StrokeThicknessProperty =
            DependencyProperty.Register("StrokeThickness", typeof(double), typeof(CircularProgressBar),
                new PropertyMetadata(10.0));

        public static readonly DependencyProperty BrushStrokeThicknessProperty =
            DependencyProperty.Register("BrushStrokeThickness", typeof(double), typeof(CircularProgressBar),
                new PropertyMetadata(1.0));

        public CircularProgressBar()
        {
            ValueChanged += CircularProgressBar_ValueChanged;
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
           
            if (Size.Width != Size.Height)
            {
                var max = Math.Max(Size.Width, Size.Height);
                Size = new Size(max, max);
            }
           
            _pathFigure = GetTemplateChild(PathFigureTemplateName) as PathFigure;
            _pathFigureAngle = GetTemplateChild(PathFigureAngleTemplateName) as PathFigure;
            _pathFigure.StartPoint = new Point(Size.Width, 0);
            _pathFigureAngle.StartPoint = new Point(Size.Width, 0);
            _arcSegment = GetTemplateChild(ArcSegmentTemplateName) as ArcSegment;
            _arcSegment.Size = Size;
            _arcSegment.Point = new Point(Size.Width - 0.000872664626, 7.61543361704753E-09);
            _arcSegmentAngle = GetTemplateChild(ArcSegmentAngleTemplateName) as ArcSegment;
            _arcSegmentAngle.Size = Size;
            _textBlock = GetTemplateChild(TextBlockTemplateName) as TextBlock;
            if (Size.Width < 15)
            {
                FontSize = 8;
            }
        }
        
        public Size Size
        {
            get => (Size)GetValue(SizeProperty);
            set => SetValue(SizeProperty, value);
        }

        public double Angle
        {
            get => (double)GetValue(AngleProperty);
            set => SetValue(AngleProperty, value);
        }

        public double StrokeThickness
        {
            get => (double)GetValue(StrokeThicknessProperty);
            set => SetValue(StrokeThicknessProperty, value);
        }

        public double BrushStrokeThickness
        {
            get => (double)GetValue(BrushStrokeThicknessProperty);
            set => SetValue(BrushStrokeThicknessProperty, value);
        }

        private void CircularProgressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var bar = sender as CircularProgressBar;
            var currentAngle = bar.Angle;
            var targetAngle = e.NewValue / bar.Maximum * 359.999;
            var anim = new DoubleAnimation(currentAngle, targetAngle, TimeSpan.FromMilliseconds(500));
            bar.BeginAnimation(AngleProperty, anim, HandoffBehavior.SnapshotAndReplace);
        }
    }
}

3) AngleToPointConverter.cs 代码如下:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace WPFDevelopers.Converts
{
    internal class AngleToPointConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var angle = (double)values[0];
            var size = (Size)values[1];
            var radius = (double)size.Height;
            var piang = angle * Math.PI / 180;

            var px = Math.Sin(piang) * radius + radius;
            var py = -Math.Cos(piang) * radius + radius;
            return new Point(px, py);
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

4) AngleToIsLargeConverter.cs 代码如下:

using System;
using System.Globalization;
using System.Windows.Data;

namespace WPFDevelopers.Converts
{
    internal class AngleToIsLargeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var angle = (double)value;
            return angle > 180;
        }

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

5) CircularMenuExample.xaml 代码如下:

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.CircularMenuExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
             xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
             xmlns:controls="clr-namespace:WPFDevelopers.Samples.Controls"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <controls:CodeViewer>
        <StackPanel Background="Black">
        <TextBlock Text="微信公众号:WPFDevelopers" FontSize="40"
                           Foreground="#A9CC32" FontWeight="Bold"
                           Margin="50,10,0,20"/>
        <wpfdev:CircularMenu ItemsSource="{Binding MenuArray,RelativeSource={RelativeSource AncestorType=local:CircularMenuExample}}" 
                             SelectionChanged="CircularMenu_SelectionChanged"/>
    </StackPanel>
        <controls:CodeViewer.SourceCodes>
            <controls:SourceCodeModel 
                CodeSource="/WPFDevelopers.SamplesCode;component/ExampleViews/CircularMenuExample.xaml" 
                CodeType="Xaml"/>
            <controls:SourceCodeModel 
                CodeSource="/WPFDevelopers.SamplesCode;component/ExampleViews/CircularMenuExample.xaml.cs" 
                CodeType="CSharp"/>
        </controls:CodeViewer.SourceCodes>
    </controls:CodeViewer>
</UserControl>

效果图

到此这篇关于WPF实现圆形进度条的示例代码的文章就介绍到这了,更多相关WPF进度条内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#实现Excel转PDF时设置内容适应页面宽度

    C#实现Excel转PDF时设置内容适应页面宽度

    将Excel转为PDF格式时,通常情况下转换出来的PDF页面都是默认的宽度大小。所以本文提供了C#实现Excel转PDF时设置内容适应页面宽度的示例代码,需要的可以参考一下
    2022-04-04
  • C#的TimeSpan案例详解

    C#的TimeSpan案例详解

    这篇文章主要介绍了C#的TimeSpan案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • WinForm实现基于BindingSource的方法扩展

    WinForm实现基于BindingSource的方法扩展

    这篇文章主要介绍了WinForm实现基于BindingSource的方法扩展,需要的朋友可以参考下
    2014-08-08
  • C#中is与as的区别分析

    C#中is与as的区别分析

    这篇文章主要介绍了C#中is与as的区别,较为详细的分析了is与as的原理与特性及用法区别,具有很好的学习借鉴价值,需要的朋友可以参考下
    2014-10-10
  • C#基础知识之GetType与typeof的区别小结

    C#基础知识之GetType与typeof的区别小结

    在比较对象时,需要了解他们的类型,才能决定他们的值是否能比较。所有的类都从System.Object中继承了GetType()方法,常常与typeo()运算符一起使用。这篇文章主要给大家介绍了关于C#基础知识之GetType与typeof区别的相关资料,需要的朋友可以参考下
    2021-06-06
  • DataGridView控件显示行号的正确代码及分析

    DataGridView控件显示行号的正确代码及分析

    今天要用到DataGridView,想给它动态的显示行号。于是在网上找了一下解决方法。结果发现了不少问题。然而就是这么一段有错的代码,几乎充斥着整个互联网,千篇一律的COPY,没有一个人纠正
    2013-08-08
  • 深入理解C#中回调函数

    深入理解C#中回调函数

    回调函数是一种在编程中常用的概念,本文将介绍回调函数的概念、语法和应用,并讨论如何设计优化和重用回调函数,以及它们在并发编程中的用途,感兴趣的可以了解一下
    2024-02-02
  • WinForm实现移除控件某个事件的方法

    WinForm实现移除控件某个事件的方法

    这篇文章主要介绍了WinForm实现移除控件某个事件的方法,对C#初学者有一定的借鉴价值,需要的朋友可以参考下
    2014-08-08
  • C#操作DataGridView设置单元格只读

    C#操作DataGridView设置单元格只读

    这篇文章介绍了C#操作DataGridView设置单元格只读的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-02-02
  • C# 异步多线程入门到精通之Thread篇

    C# 异步多线程入门到精通之Thread篇

    Thread 是 1.0 时代的产物,当时 C# 就考虑到了多线程,于是就设计了 Thread 。其实现在不推荐使用,除非在维护老的项目已经用了的。Thread 也是比较鸡肋的,有很多缺陷,但也并不是一无是处
    2021-11-11

最新评论