c# MVVM循环和更新标签与一小部分秒计时器



对于我来说,我无法让标签从0逐步更新到100。它直接到100。我想看到它的进步。我加了一个Thread.Sleep到50。看得够久了

我已经为属性更改添加了Fody,所以我不需要添加所有的绒毛,我将让注入完成它。但我尝试了传统的方法,结果一样。任何帮助或见解将是最感激的。

感谢大家的关注和帮助。

我希望看到从0到100的值迭代,中间有几分之一秒。

主窗口:

<Grid>
<view:ProcessPartsView x:Name="ProcessPartsView" />
</Grid>

控制ProcessPartsView:

<UserControl>
<Grid>
<Button x:Name="TaskButton" Command="{Binding FileLoadCommand}" />
<Label x:Name="count_parts"  Content="{Binding PartCount}" />
</Grid>
</UserControl>

后台代码:

public partial class ProcessPartsView : UserControl
{
public ProcessPartsView()
{
InitializeComponent();
DataContext = new ProcessPartsViewModel();
}
}

命令:

using System;
using System.Windows.Input;
using TEST.ViewModels;
namespace TEST.Commands
public class FileLoadCommand : ICommand
{
ProcessPartsViewModel _fileProcessViewModel;
public FileLoadCommand( ProcessPartsViewModel viewModel) 
{ 
_fileProcessViewModel = viewModel;
}
#region ICommand Members
public event EventHandler? CanExecuteChanged
{
add    { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object? parameter)
{
return true; // Button is always on
}
public void Execute(object? parameter)
{
_fileProcessViewModel.FileButtonClick();
}
#endregion
}

视图模型:

namespace TEST.ViewModels;
public class ProcessPartsViewModel : INotifyPropertyChanged
{
private int _PartCount;             
public event PropertyChangedEventHandler? PropertyChanged;
public FileLoadCommand FileLoadCommand { get; set; }
public int PartCount                
{
get { return _PartCount;  }
set { _PartCount = value; }
}
// Initialize
public ProcessPartsViewModel()
{
FileLoadCommand = new FileLoadCommand(this);  // Button on UI 
}
public void FileButtonClick()  // When the button is pressed in the view show dialog and processes selected file.
{
MessageBox.Show("I've been clicked!");
ProcessParts(); 
}
public void ProcessParts()  
{
for (int i = 0; i < 100; i++)
{
PartCount++;
Thread.Sleep(50);
}
}
}

你的ProcessParts()方法正在同步运行,因此阻塞了UI线程。

看不到任何更新,因为UI只在之后更改了方法执行完毕。这就解释了为什么它直接跳到100。您需要使用一个异步

方法。尝试使用async/await代替。使用async/await你不会阻塞UI线程:

public async void FileButtonClick()  // When the button is pressed in the view show dialog and processes selected file.
{
MessageBox.Show("I've been clicked!");
await ProcessPartsAsync(); 
}
public async Task ProcessPartsAsync()  
{
for (int i = 0; i < 100; i++)
{
PartCount++;
await Task.Delay(TimeSpan.FromMilliseconds(50));
}
}

最新更新