gpt4 book ai didi

c# - 如何使用 MVVM 模式实现进度条

转载 作者:IT王子 更新时间:2023-10-29 04:05:53 25 4
gpt4 key购买 nike

我有一个基于 MVVM 设计模式构建的 WPF 应用程序。

我希望在应用中实现一个进度条,它遵循 MVVM 模式。

有人对如何实现这一点有什么建议吗?

提前致谢

最佳答案

通常,您的 UI 会简单地绑定(bind)到 VM 中的属性:

<ProgressBar Value="{Binding CurrentProgress, Mode=OneWay}" 
Visibility="{Binding ProgressVisibility}"/>

您的 VM 将使用 BackgroundWorker在后台线程上完成工作,并定期更新 CurrentProgress 值。像这样:

public class MyViewModel : ViewModel
{
private readonly BackgroundWorker worker;
private readonly ICommand instigateWorkCommand;
private int currentProgress;

public MyViewModel()
{
this.instigateWorkCommand =
new DelegateCommand(o => this.worker.RunWorkerAsync(),
o => !this.worker.IsBusy);

this.worker = new BackgroundWorker();
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
}

// your UI binds to this command in order to kick off the work
public ICommand InstigateWorkCommand
{
get { return this.instigateWorkCommand; }
}

public int CurrentProgress
{
get { return this.currentProgress; }
private set
{
if (this.currentProgress != value)
{
this.currentProgress = value;
this.OnPropertyChanged(() => this.CurrentProgress);
}
}
}

private void DoWork(object sender, DoWorkEventArgs e)
{
// do time-consuming work here, calling ReportProgress as and when you can
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.CurrentProgress = e.ProgressPercentage;
}
}

关于c# - 如何使用 MVVM 模式实现进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3520359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com