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

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

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

有没有人对如何实现这一建议?

提前致谢

回答:

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

<ProgressBar Value="{Binding CurrentProgress, Mode=OneWay}" 

Visibility="{Binding ProgressVisibility}"/>

您的VM将使用a 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;

}

}

以上是 如何使用MVVM模式实现进度条 的全部内容, 来源链接: utcz.com/qa/419115.html

回到顶部