进度条不更新wpf?

Progress bar does not updated wpf?

我正在尝试更新 contentrendered(object sender, EventArgs e) 事件中的进度条。这是我的代码:-

MainWindow.xaml.cs

DynamicControls.ProgressBarWindow _progressBarWindow = new DynamicControls.ProgressBarWindow("Please Wait...");
_progressBarWindow.ShowDialog();

XAML

<Window x:Class="nk_Image_Converter.DynamicControls.ProgressBarWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ProgressBarWindow" Height="100" Width="500" BorderThickness="0" WindowStyle="None" ResizeMode="NoResize" Background="#d4dce6" Loaded="Window_Loaded" Initialized="Window_Initialized" ContentRendered="Window_ContentRendered" LayoutUpdated="Window_LayoutUpdated" Activated="Window_Activated" >
<Window.Effect>
    <DropShadowEffect Opacity="0.4"/>
</Window.Effect>
<Border BorderBrush="CadetBlue" BorderThickness="3,0,3,3">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0" Background="CadetBlue"></Grid>
        <Grid Grid.Row="1" Background="Transparent">
            <Label x:Name="Message" Content="Please Wait..." Margin="42,15"/>
            <ProgressBar x:Name="Progressbar" Width="400" Height="25" Margin="47,38,47,14" Foreground="CadetBlue" BorderBrush="CadetBlue" BorderThickness="2"></ProgressBar>
        </Grid>
    </Grid>
</Border>

C#

private void Window_ContentRendered(object sender, EventArgs e)
    {
        for(//Some Condition//)
        {
              Some Stuff
              Thread.sleep(100);
              this.ProgressBar.Value = //Some Value
              // above statement doesn't update the progressbar instantly

        }
    }

在上面的代码中,我希望每次给一个值时进度条移动 在 for 循环中,但它会在事件完成时更新。

您可以使用 BackroundWorker 来更新进度条的值,如下所示:

private void Window_ContentRendered(object sender, EventArgs e)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerAsync();
}


private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for(//Some Condition//)
    {
          //Some Stuff
          Thread.sleep(100);
          worker.ReportProgress(/*Some Value*/);

    }
}

BackroundWorkerSystem.ComponentModel.BackgroundWorker 命名空间中。

可以找到更多信息 here