为什么无法登录建设银行网站,wordpress 搭建wiki,网站开发项目描述,石灰土做击实检测网站怎么填【 声明#xff1a;版权所有#xff0c;欢迎转载#xff0c;请勿用于商业用途。 联系信箱#xff1a;feixiaoxing 163.com】 软件上面如果一个操作比较缓慢#xff0c;或者说需要很长的时间#xff0c;那么这个时候最好添加一个进度条#xff0c;提示一下当前任务的进展…【 声明版权所有欢迎转载请勿用于商业用途。 联系信箱feixiaoxing 163.com】 软件上面如果一个操作比较缓慢或者说需要很长的时间那么这个时候最好添加一个进度条提示一下当前任务的进展。这就是任务条的主要目的。试想一下如果我们在下载文件、烧写文件、解压文件的时候没有进度条提示我们是不是很容易误认为软件出了什么问题或者说软件是不是死锁了。而有了一个进度条之后至少可以提示我们软件还在运行所有的工作仍在推进当中只不过进度比较慢而已。 本身c# wpf也提供了进度条的控件使用也不算复杂。需要注意的一点是在vs2017或者更新一点的编译器上最好采用异步更新的方法来更新控件的内容。 1、设计界面 为了演示进度条首先需要插入进度条控件其次是label最后是按钮。当按钮按下去的时候进度条开始更新label显示百分比。它的xaml文件是这样的
Window x:ClassWpfApp.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:sysclr-namespace:System;assemblymscorlibxmlns:localclr-namespace:WpfAppmc:IgnorabledTitleProgressBarDemo Height450 Width600GridProgressBar NameprogressBar HorizontalAlignmentLeft VerticalAlignmentTop Width300 Height20 Margin20,100/Label Namelabel Content0% HorizontalAlignmentLeft VerticalAlignmentTop Width50 Height30 Margin20,150,0,0/Button ContentStart Task HorizontalAlignmentLeft VerticalAlignmentTop Margin20,200,0,0 ClickStartTask_Click//Grid
/Window如果把xaml文件转换成图形则是这样的 2、代码编写 有了界面之后下面就可以进行代码的编写。这里面最重要的实现就是按钮的回调函数。在回调函数中我们会对进度条进行更新同时也会对label的内容进行更新。相关的写法大家最好能够熟练掌握这样在后续使用的时候直接拷贝复制即可。
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows;using System.Threading.Tasks;namespace WpfApp
{/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window{ // construct functionpublic MainWindow(){InitializeComponent();}private async void StartTask_Click(object sender, RoutedEventArgs e){await Task.Run(() {int totalSteps 100;for (int i 0; i totalSteps; i1){UpdateProgressBar(i);Task.Delay(50).Wait();}});MessageBox.Show(Task finished);}private void UpdateProgressBar(int value){Application.Current.Dispatcher.Invoke(() {progressBar.Value value;label.Content Convert.ToString(value) %;});}}
}代码中最值得说的部分就是await这个操作。它本身相当于启动了一个threadawait里面的函数内容就是thread的函数体。每次递增的时候函数体会进一步调用UpdateProgressBar这个子函数里面包含了控件的更新部分即Dispatcher.Invoke操作。 而StartTask_Click函数会等待这个thread完成在操作结束之后会弹出一个消息对话框告诉用户当前任务已经完成了。 3、编译和测试 界面和代码都ok之后接下来就可以开始测试了。首先是编译编译无误之后直接单击按钮操作如果没有什么问题的话我们就会看到相关的更新和打印