wpf最简单进度条_Threading

 

<Window x:Class="WpfApp1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="gisoracle进度条" Height="200" Width="600" WindowStartupLocation="CenterScreen"
>
<Grid Margin="100,0">
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="100" />
<RowDefinition Height="Auto" />

</Grid.RowDefinitions>
<Label Name="label1" Content="进度条提示"></Label>
<ProgressBar
Name="ProgressBar"
Grid.Row="0"
Width="400"
Height="30"
Maximum="100"
Minimum="0" />
<DockPanel Grid.Row="1" LastChildFill="False">
<Button

Click="Download_OnClick"
Content="确定"
DockPanel.Dock="Right" Width="100" Height="30" />
</DockPanel>
</Grid>


</Window>

代码

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using System.Threading.Tasks;
7 using System.Windows;
8 using System.Windows.Controls;
9 using System.Windows.Data;
10 using System.Windows.Documents;
11 using System.Windows.Input;
12 using System.Windows.Media;
13 using System.Windows.Media.Imaging;
14 using System.Windows.Shapes;
15 using System.Windows.Threading;
16
17 namespace WpfApp1
18 {
19 /// <summary>
20 /// Window1.xaml 的交互逻辑
21 /// </summary>
22 public partial class Window1 : Window
23 {
24 public Window1()
25 {
26 InitializeComponent();
27 }
28
29 /// <summary>
30 /// Download按钮点击事件
31 /// </summary>
32 /// <param name="sender"></param>
33 /// <param name="e"></param>
34 private void Download_OnClick(object sender, RoutedEventArgs e)
35 {
36 Task task = new Task(TaskMethod);
37 task.Start();
38 }
39
40 private void TaskMethod()
41 {
42 for (int i = 1; i <= 100; i++)
43 {
44 Thread.Sleep(50);
45
46 Dispatcher.BeginInvoke((ThreadStart)delegate
47 {
48 if (i<=100)
49 {
50 label1.Content = i.ToString() + "%";
51 ProgressBar.Value = i;
52 }
53
54 }, DispatcherPriority.Normal);
55 }
56 }
57
58 }
59 }