WPF 弹出进度条窗口:三步轻松实现

前言

本文将介绍如何在WPF应用中实现一个弹出式进度条窗口,以便在长时间任务执行过程中向用户展示进度信息。

实现功能

模拟一个任务开始执行,在窗口弹出一个进度条,展示执行进度,执行完成弹出提示框。例如做数据查询时,如果查询需要一段时间,操作人员可以很好的知道是否查询完成。

1、设计进度条弹出窗口

进度条窗口样式设计 XAML

xml 复制代码
<Window x:Class="WpfApp.ProgressBarWindow"
        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:WpfApp"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"
        ResizeMode="NoResize"
        AllowsTransparency="True"
        Topmost="True"
        Title="ProgressBarWindow" Height="100" Width="800">
    <Grid>
        <ProgressBar Margin="5" x:Name="progressBar1"
                     HorizontalAlignment="Stretch"
                     Height="90"
                     VerticalAlignment="Center"
                     DataContext="{Binding}"
                     Value="{Binding Progress}"
                     Foreground="LightGreen"
                     >
            
        </ProgressBar>
    </Grid>
</Window>

进度窗口后台代码

c# 复制代码
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 WpfApp
{
    /// <summary>
    /// ProgressBarWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ProgressBarWindow : Window
    {
        public ProgressBarWindow()
        {
            InitializeComponent();
            DataContext = new ProgressViewModel(this);
        }
    }
}

2、创建进度条视图模型

ProgressViewModel

c# 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
 
namespace WpfApp
{
    public class ProgressViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
 
        private Window myWindow;
        public ProgressViewModel(Window wnd)
        {
            myWindow = wnd;
        }
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
 
        private int _progress;
        public int Progress
        {
            get { return _progress; }
 
            set
            {
                _progress = value;
 
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Progress)));
                if (_progress == 100)
                {
                    // 关闭进度窗口
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        myWindow.Close();
 
                    });
                }
            }
        }
    }
}

3、创建测试主窗口

主窗口XAML设计

xml 复制代码
<Window x:Class="WpfApp.MainWindow"
        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:WpfApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="400">
    <Grid>
        <Button x:Name="btnTest" FontSize="18" Click="btnTest_Click" Margin="10 30  10 30">开始任务...</Button>
    </Grid>
</Window>

主窗口后台代码

c# 复制代码
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.Navigation;
using System.Windows.Shapes;
 
namespace WpfApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
 
        private static ProgressBarWindow pgbWindow;
 
        private async void btnTest_Click(object sender, RoutedEventArgs e)
        {
 
            // 创建进度窗口
            pgbWindow = new ProgressBarWindow();
            pgbWindow.Show();
 
            // 模拟耗时任务
            await Task.Run(() =>
            {
                for (int i = 0; i <= 100; i++)
                {
                    pgbWindow.Dispatcher.Invoke(() =>
                    {
                        pgbWindow.progressBar1.Value= i;
                        Console.WriteLine(i);
                        
                    });
                    System.Threading.Thread.Sleep(20);
                }
            });
 
            MessageBox.Show("任务完成!");
        }
    }
}

4、测试验证如下

总结

从创建新的窗口到设置进度条控件,再到与后台任务的交互,每一步都详细说明了如何整合这些元素来构建一个实用的进度显示功能。这种类型的用户界面设计不仅提升了用户体验,还让应用程序看起来更加专业。

希望本教程能帮助你在自己的项目中实现类似的功能,进一步优化你的WPF应用程序。

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

也可以加入微信公众号 [DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!

优秀是一种习惯,欢迎大家留言学习!

作者:Ritchie.Lee

出处:cnblogs.com/flysh/p/18561960

声明:网络内容,仅供学习,尊重版权,侵权速删,歉意致谢!

相关推荐
有梦想的攻城狮9 分钟前
spring中的@Lazy注解详解
java·后端·spring
野犬寒鸦1 小时前
Linux常用命令详解(下):打包压缩、文本编辑与查找命令
linux·运维·服务器·数据库·后端·github
huohuopro1 小时前
thinkphp模板文件缺失没有报错/thinkphp无法正常访问控制器
后端·thinkphp
bicijinlian1 小时前
.Net HttpClient 概述
c#·.net·httpclient·.net httpclient
码观天工2 小时前
.NET 原生驾驭 AI 新基建实战系列(七):Weaviate ── 语义搜索的智能引擎创新者
ai·c#·.net·向量数据库·weaviate
Zhen (Evan) Wang2 小时前
.NET 8 + Angular WebSocket 高并发性能优化
c#·.net·angular
Zhen (Evan) Wang3 小时前
.NET 8 API 实现websocket,并在前端angular实现调用
前端·websocket·.net
chenyuhao20243 小时前
链表面试题7之相交链表
数据结构·算法·链表·面试·c#
python算法(魔法师版)4 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
cainiao0806054 小时前
《Spring Boot 4.0新特性深度解析》
java·spring boot·后端