-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
62 lines (52 loc) · 2.36 KB
/
MainWindowViewModel.cs
File metadata and controls
62 lines (52 loc) · 2.36 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace ObservableMvvm
{
public class MainWindowViewModel : BindableBase
{
private ObservableCollection<BloggerViewModel> santasBloggers = new ObservableCollection<BloggerViewModel>();
public ObservableCollection<BloggerViewModel> SantasBloggers { get => santasBloggers; set => SetProperty(ref santasBloggers, value); }
private bool useUpdateItemsExtension;
public bool UseUpdateItemsExtension { get => useUpdateItemsExtension; set => SetProperty(ref useUpdateItemsExtension, value); }
public SantasBloggerService BloggerService { get; } = new SantasBloggerService();
public WpfDispatcher Dispatcher { get; }= new WpfDispatcher();
public MainWindowViewModel()
{
Task.Run(() => UpdateBloggers());
}
private void UpdateBloggers()
{
while (true)
{
var updatedBloggers = BloggerService.GetSantasBloggers();
if (UseUpdateItemsExtension)
{
var modelToViewModelMatcher = new Func<BloggerViewModel, Blogger, bool>((vm, model) => vm.Id == model.Id);
var viewModelUpdater = new Action<BloggerViewModel, Blogger>((vm, model) => { vm.NaughtyNiceRating = model.NaughtyNiceRating; vm.JustAdded = false; });
//we have to dispatch because a .Remove or .Add to the observable has to be on the UI thread.
Dispatcher.BeginInvoke(() =>
{
SantasBloggers.UpdateItems(updatedBloggers, modelToViewModelMatcher, MapBloggerToBloggerViewModel, viewModelUpdater);
});
}
else
{
SantasBloggers = new ObservableCollection<BloggerViewModel>(updatedBloggers.Select(MapBloggerToBloggerViewModel));
}
Task.Delay(1000).Wait();
}
}
private BloggerViewModel MapBloggerToBloggerViewModel(Blogger model)
{
return new BloggerViewModel(model.Id)
{
Name = model.Name,
Blog = model.Blog,
NaughtyNiceRating = model.NaughtyNiceRating
};
}
}
}