You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.6 KiB

using ProgressBarMVVMSample.Command;
using ProgressBarMVVMSample.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace ProgressBarMVVMSample.ViewModel
{
internal class MainViewModel : BindableBase
{
private BackgroundWorker _worker;
private ICommand _startWorkCommand;
private string _title = "Progress bar MVVM Pattern";
private int _currentProgress;
private bool _progressVisibility;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public ICommand StartWorkCommand
{
get
{
Predicate<object> canExecute = (param) =>
{
if (_worker == null)
return false;
if (_worker.IsBusy)
MessageBox.Show("Background worker is busy.");
return !_worker.IsBusy;
};
return _startWorkCommand ?? (_startWorkCommand = new DelegateCommand(_worker.RunWorkerAsync, canExecute));
}
}
public int CurrentProgress
{
get { return _currentProgress; }
set { SetProperty(ref _currentProgress, value); }
}
public bool ProgressVisibility
{
get { return _progressVisibility; }
set { SetProperty(ref _progressVisibility, value); }
}
public MainViewModel()
{
InitProgressBar();
}
private void InitProgressBar()
{
_worker = new BackgroundWorker();
_worker.DoWork += DoWork;
_worker.WorkerReportsProgress = true;
_worker.ProgressChanged += ProgressChanged;
this.ProgressVisibility = false;
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.CurrentProgress = e.ProgressPercentage;
if (this.CurrentProgress == 100)
this.ProgressVisibility = false;
}
private void DoWork(object sender, DoWorkEventArgs e)
{
this.ProgressVisibility = true;
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(50);
(sender as BackgroundWorker).ReportProgress(i);
}
this.ProgressVisibility = false;
}
}
}