Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Xamarin.Forms Projects

You're reading from   Xamarin.Forms Projects Build multiplatform mobile apps and a game from scratch using C# and Visual Studio 2019

Arrow left icon
Product type Paperback
Published in Jun 2020
Publisher Packt
ISBN-13 9781839210051
Length 504 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Daniel Hindrikes Daniel Hindrikes
Author Profile Icon Daniel Hindrikes
Daniel Hindrikes
Johan Karlsson Johan Karlsson
Author Profile Icon Johan Karlsson
Johan Karlsson
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Introduction to Xamarin 2. Building Our First Xamarin.Forms App FREE CHAPTER 3. Building a News App Using Xamarin.Forms Shell 4. A Matchmaking App with a Rich UX Using Animations 5. Building a Photo Gallery App Using CollectionView and CarouselView 6. Building a Location Tracking App Using GPS and Maps 7. Building a Weather App for Multiple Form Factors 8. Setting Up a Backend for a Chat App Using Azure Services 9. Building a Real-Time Chat Application 10. Creating an Augmented Reality Game 11. Hot Dog or Not Hot Dog Using Machine Learning 12. Other Books You May Enjoy

Binding ListView in MainView

A to-do list is not much use without a list of items. Let's extend MainViewModel with a list of items:

  1. Open ViewModels/MainViewModel.cs.
  2. Add using statements for System.Collections.ObjectModel and System.Linq.
  3. Add a property for the to-do list items:
public ObservableCollection<TodoItemViewModel> Items { get; set; }

ObservableCollection is like an ordinary collection, but it has a useful superpower. It can notify listeners about changes in the list, such as when items are added or deleted. The ListView control listens to changes in the list and updates itself automatically based on these. It's important, however, to be aware that a change to an item in the list will not trigger an update. Changing the title of an item will not cause the list to re-render. Let's move on to implementing the rest of MainViewModel.

We now need some data:

  1. Open ViewModels/MainViewModel.cs.
  2. Replace (or complete) the LoadData method and create the CreateTodoItemViewModel and ItemStatusChanged methods.
  3. Resolve the reference to DoToo.Models by adding a using statement:
private async Task LoadData()
{
var items = await repository.GetItems();
var itemViewModels = items.Select(i =>
CreateTodoItemViewModel(i));
Items = new ObservableCollection<TodoItemViewModel>
(itemViewModels);
}

private TodoItemViewModel CreateTodoItemViewModel(TodoItem item)
{
var itemViewModel = new TodoItemViewModel(item);
itemViewModel.ItemStatusChanged += ItemStatusChanged;
return itemViewModel;
}

private void ItemStatusChanged(object sender, EventArgs e)
{
}

The LoadData method calls the repository to fetch all items. We then wrap each to-do list item in TodoItemViewModel. This contains more information that is specific to the view that we don't want to add to the TodoItem class. It is good practice to wrap plain objects in ViewModel; this makes it simpler to add actions or extra properties to it. ItemStatusChanged is a stub that is called when we change the status of the to-do list item from active to completed and vice versa.

We also need to hook up some events from the repository to know when data changes:

  1. Open ViewModels/MainViewModel.cs.
  2. Add the following code in bold:
public MainViewModel(TodoItemRepository repository)
{
repository.OnItemAdded += (sender, item) =>

Items.Add(CreateTodoItemViewModel(item));

repository.OnItemUpdated += (sender, item) =>
Task.Run(async () => await LoadData());

this.repository = repository;

Task.Run(async () => await LoadData());
}

When an item is added to the repository, no matter who added it, MainView will add it to the items list. Since the items collection is an observable collection, the list updates. If an item is updated, we simply reload the list.

Let's data-bind our items to ListView:

  1. Open up MainView.xaml and locate the ListView element.
  2. Modify it to reflect the following code:
<ListView Grid.Row="1"
RowHeight="70"
ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="15,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<BoxView Grid.RowSpan="2" />
<Label Grid.Column="1"
Text="{Binding Item.Title}"
FontSize="Large" />
<Label Grid.Column="1"
Grid.Row="1"
Text="{Binding Item.Due}"
FontSize="Micro" />
<Label Grid.Column="1"

Grid.Row="1"
HorizontalTextAlignment="End"
Text="Completed"
IsVisible="{Binding Item.Completed}"
FontSize="Micro" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate
>
</ListView>

The ItemsSource binding tells ListView where to find the collection to iterate over and is local to ViewModel. Any bindings in the ViewCell node, however, are local to each item that we iterate in the list. In this case, we are binding to the TodoItemViewModel, which contains a property named Item. This, in turn, has properties such as Title, Due, and Completed. We can navigate down the hierarchy of objects without any problem when defining a binding.

The DataTemplate element defines what each row will look like. We use a grid to partition the space, just as we did earlier.

You have been reading a chapter from
Xamarin.Forms Projects - Second Edition
Published in: Jun 2020
Publisher: Packt
ISBN-13: 9781839210051
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime
Visually different images