We have now finished adding navigation to a new item. Let's now add the code needed to create a new item and save it to the database:
- Open ViewModels/ItemViewModel.cs.
- Add the following code in bold.
- Resolve the reference to System.Windows.Input:
public class ItemViewModel : ViewModel
{
private TodoItemRepository repository;
public TodoItem Item { get; set; }
public ItemViewModel(TodoItemRepository repository)
{
this.repository = repository;
Item = new TodoItem() { Due = DateTime.Now.AddDays(1) };
}
public ICommand Save => new Command(async () =>
{
await repository.AddOrUpdate(Item);
await Navigation.PopAsync();
});
}
The Item property holds a reference to the current item that we want to add or edit. A new item is created in the constructor and when we want to edit an item, we can simply assign our own item to this property. The new item is not added to the database unless we execute the Save command defined at the end. After the item is added or updated, we remove the view from the navigation stack and return to MainView again.
Now that we have extended ItemViewModel with the necessary commands and properties, it's time to data-bind them in the XAML:
- Open Views/ItemView.xaml.
- Add the code marked in bold:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DoToo.Views.ItemView">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Save" Command="{Binding Save}" />
</ContentPage.ToolbarItems>
<StackLayout Padding="14">
<Label Text="Title" />
<Entry Text="{Binding Item.Title}" />
<Label Text="Due" />
<DatePicker Date="{Binding Item.Due}" />
<StackLayout Orientation="Horizontal">
<Switch IsToggled="{Binding Item.Completed}" />
<Label Text="Completed" />
</StackLayout>
</StackLayout>
</ContentPage>
The binding to the ToolbarItems command attribute triggers the Save command exposed by ItemViewModel when a user taps the Save link. It's worth noting again that any attribute called Command indicates that an action will take place and we must bind it to an instance of an object implementing the ICommand interface.
The Entry control that represents the title is data-bound to the Item.Title property of ItemViewModel, and the Datepicker and Switch controls bind in a similar way to their respective properties.
We could have exposed Title, Due, and Complete as properties directly on ItemViewModel, but we instead chose to reuse the already-existing TodoItem object as a reference. This is fine, as long as the properties of the TodoItem object implement the INotifyPropertyChange interface.