当前位置: 首页 > article >正文

WPF创建进度条

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

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

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

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

<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,要相对的扩大或者缩小,那么界面上显示的数据变化就是一样的。

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

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,最后就是对进度条的美化样式

<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博客


http://www.kler.cn/a/148382.html

相关文章:

  • datastage在升级版本到11.7之后,部分在11.3上正常执行的SP报错SQLSTATE = 22007: 本机错误代码 = -180
  • u盘加密软件有哪些?2025年必备的u盘加密神器分享(共6款!提前布局!)
  • SpringBoot实战(三十一)集成iText5,实现RSA签署PDF
  • Linux基础1
  • HBase使用create创建表时报错ERROR: KeeperErrorCode = NoNode for /hbase/master
  • 数据库SQL——连接表达式(JOIN)图解
  • 「计算机网络」Cisco Packet Tracker计算机网络仿真器的使用
  • YOLOv5算法进阶改进(5)— 主干网络中引入SCConv | 即插即用的空间和通道维度重构卷积
  • android项目之调用webview
  • TypeScript学习记录
  • LeetCode51. N-Queens
  • java后端实现登录退出功能,并用过滤器验证
  • android trace文件的抓取与查看方法
  • 【Lidar】基于Python的点云数据下采样+体素显示
  • tauri中使用rust调用动态链接库例子(使用libloading库和libc库)
  • ubuntu22.04 arrch64版在线安装java环境
  • C语言-指针讲解(3)
  • 用通俗的方式讲解Transformer:从Word2Vec、Seq2Seq逐步理解到GPT、BERT
  • 人机交互3——多主题多轮对话
  • TOD和PPS精确时间同步技术
  • C#面向对象
  • 2023网络安全产业图谱
  • 02-Java集合之双列集合,如HashMap,Hashtable,Properties,TreeMap的底层结构
  • 人工智能技术发展漫谈
  • 【Linux】信号
  • 《2023全球隐私计算报告》正式发布!