0

我正在实现一个 ProgressBar,它在每个完成的任务(总共 5 个任务)后更新。每个完成任务后它应该更新 20%。单击按钮开始运行任务,但是当它被单击时,进度条从 0% 变为 100%,而在两者之间没有更新。Thread.Sleep(1000) 在进度值的每个增量之前添加,以模拟每个任务将花费的时间。我想在为每个任务添加代码之前让进度条工作。

我尝试添加 AvaloniaPropertyChanged 事件,但似乎并没有改变问题。

MainWindow.xaml:

<ProgressBar Name="RunProgress" Value="{Binding Progress}" IsIndeterminate="False" Minimum="0" Maximum="100" Height="30"/>
<TextBlock Text="{Binding ElementName=RunProgress, Path=Value, StringFormat={}{0:0}%}" HorizontalAlignment="Center" VerticalAlignment="Center" />

MainWindow.xaml.cs:

//boolean variables for whether or not that process is completed (false if not done, true if done)
bool MasterLimitsRead = false;
bool MasterOrganized = false;
bool LimitsOrganized = false;
bool RemovedFailed = false;
bool OutputCreated = false;

//holds descriptions of the 5(+1) operations the program runs through including description for Done
string[] operation =
{
   "Reading the master and limits file text",
   "Organizing the master data",
   "Organizing the limits",
   "Identifying and removing failed devices",
   "Creating the output",
   "Done"
};

context.CurrentOp = operation[0];

Thread.Sleep(1000);
MasterLimitsRead = true;
if(MasterLimitsRead == true)
{
   context.Progress += 20;
   context.CurrentOp = operation[1];
}

Thread.Sleep(1000);
MasterOrganized = true;
if(MasterOrganized == true)
{
   context.Progress += 20;
   context.CurrentOp = operation[2];
}

Thread.Sleep(1000);
LimitsOrganized = true;
if(LimitsOrganized == true)
{
   context.Progress += 20;
   context.CurrentOp = operation[3];
}

Thread.Sleep(1000);
RemovedFailed = true;
if(RemovedFailed == true)
{
   context.Progress += 20;
   context.CurrentOp = operation[4];
}

Thread.Sleep(1000);
OutputCreated= true;
if(OutputCreated== true)
{
   context.Progress += 20;
   context.CurrentOp = operation[5];
}

MainWindowViewModel.cs:

private string currentOp = string.Empty;   //variable to store current operation, initialized to empty string
public string CurrentOp
{
   get => currentOp;
   set
   {
      if (value != currentOp)
      {
         currentOp = value;
         OnPropertyChanged();
      }
    }
}

private string progress = 0;   //variable to store ProgressBar value in percent, initialized to 0
public string CurrentOp
{
   get => currentOp;
   set
   {
      if (value != currentOp)
      {
         currentOp = value;
         OnPropertyChanged();
      }
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
   if(PropertyChanged != null)
   {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
}

预期:在每个任务完成后,进度条应从 0% 增加到 100%,增量为 20%(由 Thread.Sleep(1000) 模拟 1 秒延迟)

实际:进度条从 0% 开始,然后当单击按钮时,暂停 UI 交互 5 秒,然后将进度条更新为 100%。我希望它在进度条值的每次增量时更新。

4

1 回答 1

1

通过调用Sleep您正在阻塞 UI 线程。如果 UI 线程被阻塞,则不会有任何 UI 更新。要模拟长时间运行的任务,请await Task.Delay(TimeSpan.FromSeconds(1))改用。

于 2019-06-25T04:42:24.653 回答