master
1using System;
2using System.Collections.Generic;
3using System.Collections.ObjectModel;
4using System.ComponentModel;
5using System.Linq;
6using System.Linq.Expressions;
7using System.Windows.Input;
8using MVPtoMVVM.domain;
9using MVPtoMVVM.repositories;
10
11namespace MVPtoMVVM.mvvm.viewmodels
12{
13 public class MainWindowViewModel : INotifyPropertyChanged
14 {
15 private ITodoItemRepository todoItemRepository;
16 private Synchronizer<MainWindowViewModel> updater;
17 public event PropertyChangedEventHandler PropertyChanged = (o, e) => { };
18 public ICollection<TodoItemViewModel> TodoItems { get; set; }
19 public ICommand CancelChangesCommand { get; set; }
20 public ICommand AddNewItemCommand { get; set; }
21
22 public MainWindowViewModel(ITodoItemRepository todoItemRepository)
23 {
24 this.todoItemRepository = todoItemRepository;
25 AddNewItemCommand = new SimpleCommand(AddNewItem);
26 CancelChangesCommand = new SimpleCommand(RefreshChanges);
27 updater = new Synchronizer<MainWindowViewModel>(() => PropertyChanged);
28 TodoItems = new ObservableCollection<TodoItemViewModel>();
29 RefreshChanges();
30 }
31
32 private void RefreshChanges()
33 {
34 TodoItems.Clear();
35 foreach (var item in todoItemRepository.GetAll().Select(MapFrom))
36 {
37 TodoItems.Add(item);
38 }
39 }
40
41 private void AddNewItem()
42 {
43 TodoItems.Add(new TodoItemViewModel(todoItemRepository){Parent = this, DueDate = DateTime.Today, Description = string.Empty, IsDirty = false});
44 }
45
46 private TodoItemViewModel MapFrom(TodoItem item)
47 {
48 return new TodoItemViewModel(todoItemRepository)
49 {
50 Id = item.Id,
51 Description = item.Description,
52 DueDate = item.DueDate,
53 Parent = this,
54 IsDirty = false,
55 };
56 }
57
58 public void Update(Expression<Func<MainWindowViewModel, object>> property)
59 {
60 updater.Update(this, property);
61 }
62 }
63}