且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用进度条

更新时间:2023-01-13 09:41:52

我在使用WPF时也遇到过这个问题,你可能需要这样的东西:

I experienced this problem too when starting with WPF, you probably need something like this:
progressbar1.Dispatcher.Invoke(() => progressbar1.Value = i, DispatcherPriority.Background);

参见: c# - 实时更新进度条wpf - 堆栈溢出 [ ^ ]


请看一下这个例子:



MainWindow .xaml

Please have a look at this example:

MainWindow.xaml
<Window x:Class="WpfApplication3.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"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ProgressBar Name="ProgressBar" Height="20"></ProgressBar>
    </Grid>
</Window>



MainWindow.xaml.cs


MainWindow.xaml.cs

using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication3
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            ProgressBar.Minimum = 0;
            ProgressBar.Maximum = 100;
            ProgressBar.Value = 0;

            DoIt();
        }

        public void DoIt()
        {
            var task = new Task(() =>
            {
                for (var i = 0; i <= 100; i++)
                {
                    SetProgressBarValue(i);

                    // Simulate some work...
                    Thread.Sleep(100);
                }
            });

            task.Start();
        }

        public void SetProgressBarValue(int value)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                ProgressBar.Value = value;
            });
        }
    }
}