Introduction
In this tutorial, we will walk through the process of building a todo list app using C# and Xamarin. Xamarin is a cross-platform development framework that allows us to write applications for Android, iOS, and Windows using the .NET language. We will use Visual Studio as our IDE to develop and build the app.
The app we are going to build will have the following functionality:
– Ability to add tasks to the todo list
– Ability to mark tasks as completed
– Ability to delete tasks from the todo list
– Ability to filter tasks based on their completion status
By the end of this tutorial, you will have a functioning todo list app that you can run on Android and iOS devices.
Prerequisites
To follow along with this tutorial, you will need the following:
- Visual Studio 2019 (or later) with the following workloads installed:
- Mobile development with .NET (Xamarin)
- An Android or iOS device or emulator to run the app on.
Step 1: Create a new Xamarin.Forms project
Let’s start by creating a new Xamarin.Forms project in Visual Studio:
- Open Visual Studio and select “Create a new project”.
- In the search box, type “Mobile App (Xamarin.Forms)” and select the template.
- Choose a name and location for your project, and click “Create”.
- In the next dialog, select “Blank” as the template and check both “Android” and “iOS” projects.
- Click “Create” to create the project.
Visual Studio will create a new Xamarin.Forms project with 3 projects: a shared .NET Standard library, an Android project, and an iOS project.
Step 2: Design the user interface
Next, we will design the user interface for our app. Open the MainPage.xaml
file in the shared project and replace the existing XAML code with the following:
<ContentPage
xmlns_x="http://schemas.microsoft.com/winfx/2009/xaml"
x_Class="TodoListApp.MainPage"
Title="Todo List">
<ContentPage.Content>
<StackLayout>
<ListView x_Name="taskListView" ItemsSource="{Binding Tasks}"
HasUnevenRows="True" SelectionMode="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="10">
<CheckBox IsChecked="{Binding IsCompleted}" />
<Label Text="{Binding Description}" VerticalTextAlignment="Center" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout Orientation="Horizontal" Padding="10,0">
<Entry x_Name="taskEntry" Placeholder="Enter task description" />
<Button Text="Add" Clicked="OnAddClicked" />
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
In this XAML code, we have a ListView
control that will display our tasks. Each task is represented by a ViewCell
containing a CheckBox
to mark the task as completed and a Label
to display the task description.
We also have an Entry
control and a Button
control at the bottom of the page, which will allow the user to add new tasks to the list.
Step 3: Create the model class
Next, let’s create a model class to represent a task. Right-click on the shared project and select “Add -> Class”. Name the class TaskItem.cs
and replace the code with the following:
using System.ComponentModel;
namespace TodoListApp
{
public class TaskItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string description;
private bool isCompleted;
public string Description
{
get { return description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged(nameof(Description));
}
}
}
public bool IsCompleted
{
get { return isCompleted; }
set
{
if (isCompleted != value)
{
isCompleted = value;
OnPropertyChanged(nameof(IsCompleted));
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
This class implements the INotifyPropertyChanged
interface, which allows us to notify the UI when a property changes. It has two properties: Description
, which represents the task description, and IsCompleted
, which represents whether the task is completed or not.
Step 4: Implement the view model
Now, let’s create a view model class to manage the data and interaction with the UI. Right-click on the shared project and select “Add -> Class”. Name the class MainViewModel.cs
and replace the code with the following:
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace TodoListApp
{
public class MainViewModel
{
public ObservableCollection<TaskItem> Tasks { get; } = new ObservableCollection<TaskItem>();
public void AddTask(string description)
{
Tasks.Add(new TaskItem { Description = description });
}
}
}
This view model class contains an ObservableCollection
of TaskItem
objects, which will store our tasks. It also has a method AddTask
that adds a new task to the collection.
Step 5: Update the code-behind file
Next, let’s update the code-behind file for the MainPage
to integrate the view model with the UI. Open the MainPage.xaml.cs
file and replace the code with the following:
using Xamarin.Forms;
namespace TodoListApp
{
public partial class MainPage : ContentPage
{
private MainViewModel viewModel = new MainViewModel();
public MainPage()
{
InitializeComponent();
BindingContext = viewModel;
}
private void OnAddClicked(object sender, EventArgs e)
{
string description = taskEntry.Text;
if (!string.IsNullOrWhiteSpace(description))
{
viewModel.AddTask(description);
taskEntry.Text = string.Empty;
}
}
}
}
In the constructor, we set the BindingContext
of the page to an instance of the MainViewModel
class. This allows us to bind the Tasks
property of the view model to the ItemsSource
property of the ListView
in the XAML code.
We also handle the “Add” button click event to add a new task to the view model and clear the text input.
Step 6: Test the app on Android
Now, let’s test the app on an Android device or emulator:
- Set the Android project as the startup project by right-clicking on the Android project in the solution explorer and selecting “Set as StartUp Project”.
- Select your Android device or emulator from the device dropdown in Visual Studio.
- Click the “Start Debugging” button to build and deploy the app to the selected device or emulator.
Once the app is running, you should be able to add tasks to the list and mark them as completed by tapping on the checkboxes.
Step 7: Test the app on iOS
Next, let’s test the app on an iOS device or simulator:
- Set the iOS project as the startup project by right-clicking on the iOS project in the solution explorer and selecting “Set as StartUp Project”.
- Select your iOS device or simulator from the device dropdown in Visual Studio.
- Click the “Start Debugging” button to build and deploy the app to the selected device or simulator.
Once the app is running, you should see the same functionality as on the Android device or emulator.
Conclusion
In this tutorial, we have built a todo list app using C# and Xamarin. We learned how to create a user interface, implement a view model, and integrate the UI with the view model. We also tested the app on Android and iOS devices.
You can further enhance the app by adding features like task filtering, editing tasks, and persisting tasks using a local database. This tutorial serves as the foundation for building more complex Xamarin apps with C#. Happy coding!