/
LoaderBase.cs
49 lines (44 loc) · 1.28 KB
/
LoaderBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using Dietphone.Models;
using System.ComponentModel;
namespace Dietphone.ViewModels
{
public abstract class LoaderBase
{
public event EventHandler Loaded;
protected Factories factories;
protected bool isLoading;
protected SubViewModel viewModel;
public void LoadAsync()
{
if (viewModel == null)
{
throw new InvalidOperationException("Pass ViewModel in constructor for this operation.");
}
if (isLoading)
{
return;
}
var worker = new BackgroundWorker();
worker.DoWork += delegate { DoWork(); };
worker.RunWorkerCompleted += delegate { WorkCompleted(); };
viewModel.IsBusy = true;
isLoading = true;
worker.RunWorkerAsync();
}
protected abstract void DoWork();
protected virtual void WorkCompleted()
{
viewModel.IsBusy = false;
isLoading = false;
OnLoaded();
}
protected void OnLoaded()
{
if (Loaded != null)
{
Loaded(this, EventArgs.Empty);
}
}
}
}