Next up is the second view. We will use this to add and edit the to-do list items:
- Create a new content page (in the same way that we created the MainView view) and name it ItemView.
- Edit the XAML file so that it appears as in the following code:
<?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"
Title="New todo item">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Save" />
</ContentPage.ToolbarItems>
<StackLayout Padding="14">
<Label Text="Title" />
<Entry />
<Label Text="Due" />
<DatePicker />
<StackLayout Orientation="Horizontal">
<Switch />
<Label Text="Completed" />
</StackLayout>
</StackLayout>
</ContentPage>
As with MainView, we need a title. We will give it a default title of New todo item for now, but we will change this to Edit todo item when we reuse this view for editing later on. The user must be able to save a new or edited item, so we have added a toolbar save button. The content of the page uses StackLayout to structure the controls. StackLayout adds an element vertically (the default option) or horizontally based on the space it calculates that the element takes up. This is a CPU-intensive process, so we should only use it on small portions of our layout. In StackLayout, we add a Label control that is a line of text over the Entry control that comes underneath it. The Entry control is a text input control that contains the name of the to-do list item. We then have a section for DatePicker, where the user can select a due date for the to-do list item. The final control is a Switch control, which renders a toggle button to control when an item is complete, as well as a heading next to it. Since we want these to be displayed next to each other horizontally, we use a horizontal StackLayout control to do this.
The last step for the views is to wire up the ItemViewModel model to ItemView:
- Open up the code-behind file of ItemView by expanding the ItemView.xaml file in Solution Explorer.
- Modify the constructor of the class to appear as in the following code. Add the code that is marked in bold:
public ItemView (ItemViewModel viewmodel)
{
InitializeComponent ();
viewmodel.Navigation = Navigation;
BindingContext = viewmodel;
}
- Add a using DoToo.ViewModels statement at the top of the file, adjacent to the existing using statements:
using DoToo.ViewModels;
This code is identical to the code that we added for MainView, except for the type of ViewModel class.