我正在实现一个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%。我希望它在进度栏的每个值增量时更新。
答案 0 :(得分:0)
通过调用Sleep
,您正在阻止UI线程。如果UI线程被阻止,则不会进行任何UI更新。要模拟长时间运行的任务,请改用await Task.Delay(TimeSpan.FromSeconds(1))
。