We’ve seen how to get a single zip code and display it in a series of labels. Let’s use a collection to take a look at how we might deal with that in MAUI. To get started, we’ll create a new MAUI application named MultipleZip. Throw away what is in MainPage.xaml and MainPage.xaml.cs. You should have a nice clean slate.
In the new project, create a Model folder. Now open a second Visual Studio, navigate to the previous application from Part 3, and copy the City.cs, Result.cs, and Root.cs files. Return to our new project and paste those right into the models folder. That will save us recreating these model files.
CollectionView
In MainPage let’s create a CollectionView. This will ultimately hold multiple zip code information, but for now we’re going to hand populate it.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MultipleZip.MainPage">
<CollectionView>
<CollectionView.ItemsSource>
</CollectionView.ItemsSource>
</CollectionView>
</ContentPage>
ItemsSource will take any kind of collection including an array. We can create an array here and populate it.
To start, go up to the namespaces and enter
xmlns:model="model"
You will see a drop down of all the models. Just tap on ours (ZipCode)
Now we can populate our collection view. In the ItemsSource elements enter
<x:Array Type="{x:Type model:Results}
When you type model, all of the model types will come up; in this case we want Results.
Enter a few zip codes using one of its properties, in this case country.
<x:Array Type="{x:Type model:Results}">
<model:Results country="USA" />
<model:Results country="France" />
<model:Results country="United Kingdom" />
</x:Array>
If we run this now we won’t quite get what we want because we need a datatemplate to display it (this should all be very familiar):
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Results">
<VerticalStackLayout>
<Label Text="{Binding country}" />
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
Now we are all set, and when we run this we see the three countries (again, not nicely laid out, but there, which is the important part.
In an upcoming blog post we’ll see how to get this data from our service and display it in a CollectionView.
The source code is available here Note, being less than a genius I managed to overwrite this repository with the code from the next blog post.