This week we’ll save the Tasks in memory, in coming weeks we’ll review databinding and we’ll review the tasks in a bound list.
NB: We’re moving very quickly through the preliminaries, so please do use the comments to ask questions or let me know where there are areas of confusion.
The Model
The first job is to create a task model: a class whose instances can each represent one task.
Let’s call it ToDoItem,
public class ToDoItem {
public string TaskName { get; set; }
public string Priority { get; set; }
public DateTime DueDate { get; set; }
public bool IsDeleted { get; set; }
}
I can be pretty sure that at some point I’ll want to move this to a database, and I’ll need an ID field, but the YAGNI* design principle says that I should wait, and so for now no ID is included.
Saving Tasks
With that in place, we can pretty easily write the code to save each task to a collection. We already have a CreatePage.xaml file, let’s create the corresponding CreatePageViewModel file in the ViewModel folder. In this file we can add a collection of ToDoItems and we can add a method, AddToDoItem,
public List<ToDoItem> ToDoItems = new List<ToDoItem>();
public void AddToDoItem(
string todo,
string priority,
DateTime dueDate,
int hour,
int minute,
int second) {
var newToDo = new ToDoItem {
TaskName = todo,
Priority = priority,
DueDate = SetDueDate(dueDate, hour, minute, second)
};
ToDoItems.Add(newToDo);
}
public DateTime SetDueDate(DateTime date, int hour, int minute, int second) {
DateTime retVal = new DateTime(
date.Year,
date.Month,
date.Day,
hour,
minute,
second);
return retVal;
}
Notice that we can get a DateTime for the DueDate but the time comes in as hour, minute and second. That is because the DatePicker returns a DateTime but the TimePicker returns a TimeSpan.
In the code-behind for the view, we create an instance of the ViewModel which we instantiate in the constructor,
private CreatePageViewModel vm;
public CreatePage() {
vm = new CreatePageViewModel();
InitializeComponent();
}
We then implement OnSaveClicked to pass the data to the ViewModel where it will be instantiated as a ToDoItem and added to the list.
public void OnSaveClicked(object o, EventArgs e) {
vm.AddToDoItem(
ToDo.Text,
Priority.Text,
Date.Date,
Time.Time.Hours,
Time.Time.Minutes,
Time.Time.Seconds);
}
You can see that we’ve begun to move the logic of the program to the VM, where it belongs.
*YAGNI = You Ain’t Gonna’ Need It