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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using MVPtoMVVM.domain;
using MVPtoMVVM.repositories;
using System.Linq;
namespace MVPtoMVVM.mvvm.viewmodels
{
public class TodoItemViewModel : INotifyPropertyChanged, IDataErrorInfo
{
private readonly ITodoItemRepository todoItemRepository;
private Synchronizer<TodoItemViewModel> synchronizer;
public event PropertyChangedEventHandler PropertyChanged = (o, e) => { };
public int Id { get; set; }
public IObservableCommand SaveCommand { get; set; }
public IObservableCommand DeleteCommand { get; set; }
public MainWindowViewModel Parent { get; set; }
private IDictionary<string, IValidation> validations;
public bool IsDirty { get; set; }
public TodoItemViewModel(ITodoItemRepository todoItemRepository)
{
this.todoItemRepository = todoItemRepository;
SaveCommand = new SimpleCommand(Save, CanSave);
DeleteCommand = new SimpleCommand(Delete);
synchronizer = new Synchronizer<TodoItemViewModel>(() => PropertyChanged);
validations = new Dictionary<string, IValidation>
{
{"Description", new Validation(() => !string.IsNullOrEmpty(Description), "Cannot have an empty description.")},
{"DueDate", new Validation(() => DueDate >= DateTime.Today, "Due Date must occur on or after today.")}
};
}
private void Delete()
{
todoItemRepository.Delete(Id);
Parent.TodoItems.Remove(this);
}
private bool CanSave()
{
return validations.Values.All(x => x.IsValid) && IsDirty;
}
private void Save()
{
var todoItem = todoItemRepository.Get(Id) ?? new TodoItem();
todoItem.DueDate = DueDate;
todoItem.Description = Description;
todoItemRepository.Save(todoItem);
IsDirty = false;
}
private string description;
public string Description
{
get { return description; }
set
{
description = value;
IsDirty = true;
Update(x => x.Description);
SaveCommand.Changed();
}
}
private void Update(Expression<Func<TodoItemViewModel, object>> func)
{
synchronizer.Update(this, func);
}
private DateTime dueDate;
public DateTime DueDate
{
get { return dueDate; }
set
{
dueDate = value;
IsDirty = true;
Update(x => x.DueDate);
Update(x => x.ShowDueSoonAlert);
SaveCommand.Changed();
}
}
public Visibility ShowDueSoonAlert
{
get
{
return DueDate <= DateTime.Today.AddDays(1) ? Visibility.Visible : Visibility.Hidden;
}
}
public string this[string columnName]
{
get
{
var validation = validations[columnName];
return validation.IsValid ? null : validation.Message;
}
}
public string Error
{
get { return string.Empty; }
}
}
}
|