我有一个基于MVVM设计模式的WPF应用程序。
我希望在应用程序中实现一个遵循MVVM模式的进度条。
有人对如何实现这个有任何建议吗?
提前致谢
答案 0 :(得分:54)
通常,您的UI只会绑定到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;
}
}
答案 1 :(得分:10)
使用ProgressBar
控件并将其Value
属性绑定到ViewModel的属性:
查看强>
<ProgressBar Minimum="0" Maximum="0" Value="{Binding CurrentProgress}" />
<强>视图模型强>
private double _currentProgress;
public double CurrentProgress
{
get { return _currentProgress; }
private set
{
_currentProgress = value;
OnPropertyChanged("CurrentProgress");
}
}
答案 2 :(得分:6)
向VM添加两个属性:
bool IsProgressBarVisible
double ProgressValue
如果在VM中启动长时间操作,请将IsProgressBarVisible属性设置为true,并将ProgressValue周期设置为当前进度值。尝试计算0到100之间的值。这样做的好处是您不必提供最小值和最大值。 异步操作完成后,将IsProgressBarVisible设置为false。
在XAML中,绑定到这两个属性。使用值转换器将布尔可见性转换为可见性。
<ProgressBar Value="{Binding ProgressValue}" Visibility="{Binding IsProgressBarVisible,Converter={StaticResource BooleanToVisibility_ValueConverter}}"/>