WPF创建进度条

使用wpf做一个原生的进度条,进度条上面有值,先看效果。

功能就是点击按钮,后台处理数据,前台显示处理数据的变化,当然还可以对进度条进行美化和关闭的操作,等待后台处理完毕数据,然后自动关闭。

1.首先简简单单创建一个项目

2.先建立进度条的页面DialogWait.xaml

cs 复制代码
<Window x:Class="WpfApp5.DialogWait"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp5"
        mc:Ignorable="d"
        WindowStyle="None" AllowsTransparency="True"  Background="Transparent" ShowInTaskbar="False" ResizeMode="NoResize">
    <ProgressBar x:Name="progressBar" Maximum="100"   Height="25" Width="300" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
</Window>

3.DialogWait.xaml.cs后台代码如下

关键点就是要对max的值进行判断,如果大于100和小于100的话,显示是不一样的,主要是因为进度条的值是100,要相对的扩大或者缩小,那么界面上显示的数据变化就是一样的。

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp5
{
    /// <summary>
    /// DialogWait.xaml 的交互逻辑
    /// </summary>
    public partial class DialogWait : Window
    {
        /// <summary>
        /// 进度条最大值
        /// </summary>
        private int max = 0;
        /// <summary>
        /// 大于100的增量
        /// </summary>
        private int increment = 0;
        /// <summary>
        /// 小于100的增量
        /// </summary>
        private double incrementLess = 0;
        public DialogWait()
        {
            InitializeComponent();
        }
        public DialogWait(int max)
        {
            InitializeComponent();
            this.Width = 300;
            this.Height = 25;
            this.Owner = Application.Current.MainWindow;
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            this.max = max;
            if (max >= 100)
            {
                increment = max / 100;
            }
            else
            {
                incrementLess = Math.Round(100.0 / max, 3);
            }
        }
        public void ShowWait(int value)
        {
            progressBar.Dispatcher.Invoke(() =>
            {
                if (max >= 100)
                {
                    progressBar.Value = value / increment;
                }
                else
                {
                    progressBar.Value = Math.Round(value * incrementLess, 0);
                }
            });
        }
    }
}

4.MainWindow.xaml.cs的代码

其中最重要的就是Task

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp5
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DialogWait dialogWaitPercent = new DialogWait(500);
            Task.Run(() =>
            {
                A(dialogWaitPercent);//处理数据
            });
            dialogWaitPercent.ShowDialog();
        }
        public void A(DialogWait dialogWaitPercent)
        {
            for (int i = 0; i < 500; i++)
            {
                dialogWaitPercent.ShowWait(i);
                Thread.Sleep(10);
            }
            dialogWaitPercent.Dispatcher.Invoke(() =>
            {
                dialogWaitPercent.Close();
            });
        }
    }
}

5.ProgressBarStyle.xaml,最后就是对进度条的美化样式

cs 复制代码
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type ProgressBar}">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="Height" Value="15"/>
        <Setter Property="Background" Value="#6fae5f"/>
        <Setter Property="FontSize" Value="10"/>
        <Setter Property="Padding" Value="5,0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ProgressBar}">
                    <Grid Background="#00000000">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Determinate"/>
                                <VisualState x:Name="Indeterminate">
                                    <Storyboard RepeatBehavior="Forever">
                                        <PointAnimationUsingKeyFrames Storyboard.TargetName="Animation" Storyboard.TargetProperty="(UIElement.RenderTransformOrigin)">
                                            <EasingPointKeyFrame KeyTime="0:0:0" Value="0.5,0.5"/>
                                            <EasingPointKeyFrame KeyTime="0:0:1.5" Value="1.95,0.5"/>
                                            <EasingPointKeyFrame KeyTime="0:0:3" Value="0.5,0.5"/>
                                        </PointAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

                        <Grid Height="{TemplateBinding Height}">
                            <Border Background="#000000" CornerRadius="7.5" Opacity="0.05"/>
                            <Border BorderBrush="#000000" BorderThickness="1" CornerRadius="7.5" Opacity="0.1"/>
                            <Grid Margin="{TemplateBinding BorderThickness}">
                                <Border x:Name="PART_Track"/>
                                <Grid x:Name="PART_Indicator" ClipToBounds="True" HorizontalAlignment="Left" >
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition x:Name="width1"/>
                                        <ColumnDefinition x:Name="width2" Width="0"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid x:Name="Animation"  RenderTransformOrigin="0.5,0.5">
                                        <Grid.RenderTransform>
                                            <TransformGroup>
                                                <ScaleTransform ScaleY="-1" ScaleX="1"/>
                                                <SkewTransform AngleY="0" AngleX="0"/>
                                                <RotateTransform Angle="180"/>
                                                <TranslateTransform/>
                                            </TransformGroup>
                                        </Grid.RenderTransform>
                                        <Border Background="{TemplateBinding Background}" CornerRadius="7.5">
                                            <Viewbox HorizontalAlignment="Left" StretchDirection="DownOnly" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="True">
                                                <TextBlock Foreground="#ffffff" SnapsToDevicePixels="True" FontSize="{TemplateBinding FontSize}" VerticalAlignment="Center" Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Value,StringFormat={}{0}%}" RenderTransformOrigin="0.5,0.5">
                                                    <TextBlock.RenderTransform>
                                                        <TransformGroup>
                                                            <ScaleTransform ScaleY="1" ScaleX="-1"/>
                                                            <SkewTransform AngleY="0" AngleX="0"/>
                                                            <RotateTransform Angle="0"/>
                                                            <TranslateTransform/>
                                                        </TransformGroup>
                                                    </TextBlock.RenderTransform>
                                                </TextBlock>
                                            </Viewbox>
                                        </Border>
                                        <Border BorderBrush="#000000" BorderThickness="1" CornerRadius="7.5" Opacity="0.1"/>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                    <ControlTemplate.Triggers>

                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Background" Value="#c5c5c5"/>
                        </Trigger>
                        <Trigger Property="IsIndeterminate" Value="true">
                            <Setter TargetName="width1" Property="Width" Value="0.25*"/>
                            <Setter TargetName="width2" Property="Width" Value="0.725*"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

本案例代码:https://download.csdn.net/download/u012563853/88578158

来源:WPF创建进度条-CSDN博客

相关推荐
玖笙&3 天前
✨WPF编程基础【2.1】布局原则
c++·wpf·visual studio
玖笙&3 天前
✨WPF编程基础【2.2】:布局面板实战
c++·wpf·visual studio
SEO-狼术3 天前
.NET WPF 数据编辑器集合提供列表框控件
.net·wpf
FuckPatience7 天前
WPF 具有跨线程功能的UI元素
wpf
诗仙&李白7 天前
HEFrame.WpfUI :一个现代化的 开源 WPF UI库
ui·开源·wpf
He BianGu7 天前
【笔记】在WPF中Binding里的详细功能介绍
笔记·wpf
He BianGu7 天前
【笔记】在WPF中 BulletDecorator 的功能、使用方式并对比 HeaderedContentControl 与常见 Panel 布局的区别
笔记·wpf
123梦野8 天前
WPF——效果和可视化对象
wpf
He BianGu8 天前
【笔记】在WPF中Decorator是什么以及何时优先考虑 Decorator 派生类
笔记·wpf
时光追逐者8 天前
一款专门为 WPF 打造的开源 Office 风格用户界面控件库
ui·开源·c#·.net·wpf