如何使用 MVVM 模式实现进度条 [英] How to implement a progress bar using the MVVM pattern

查看:32
本文介绍了如何使用 MVVM 模式实现进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WPF application which is built on the MVVM design pattern.

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

I wish to implement a progress bar in the app, that follows the MVVM pattern.

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

Does any one have any suggestions on how to implement this?

提前致谢

推荐答案

通常,您的 UI 只会绑定到 VM 中的属性:

Typically your UI would simply bind to properties in your VM:

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

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

Your VM would use a BackgroundWorker to do the work on a background thread, and to periodically update the CurrentProgress value. Something like this:

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 模式实现进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆