Category Archives: XAML

Xamarin Forms: ListView with SQLite

Previously we stored our entry in a SQLite database. Now we want to be able to look at a list of the things we previously saved.

ListView

When you want to display a list of objects, your best option is most likely the aptly named ListView. The ListView binds to a dataset and then displays each item according to a template in a scrollable list.

This is exactly what we want to use to view our saved properties for the cashflow calculator.

Getting the Data

There are several ways to get the data out of the SQLite database and into the ListView. Two of the most common ways are returning the result to a List or creating a CursorAdapter.

I chose to use the List method as it is simple and worked well with how I have set up the database calls to be asynchronous.

A New Page

We need to create a SavedProperties Page and set up our ListView there.

In the XAML file, we need to create our ListView and our template for each item. For now I just want to display the property name and its value.


<?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="SimpleCashflowCalculator.SavedPropertiesPage">
    <ListView x:Name="saved_properties_list">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal" 
                        HorizontalOptions="FillAndExpand"
                        Margin="20, 10, 20, 0" >
                        <Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" />
                        <Label Text="{Binding Value}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

This creates a ListView called saved_properties_list and gives it an item template with 2 text labels. It is now expecting a Name field and a Value field for whatever objects are bound to this ListView.

Setting the ItemSource

The way to actually tell the ListView which dataset to use is by setting its ItemSource. We want to refresh this view every time we switch to it so that it always has the latest data. To do that we are going to set the ItemSource in the OnAppearing event.


        protected override async void OnAppearing()
        {
            base.OnAppearing();
            saved_properties_list.ItemsSource = await SimpleCashflowCalculatorPage.Database.GetPropertiesAsync();
        }

This is a parent class method so we override it and then call what is often called the super method or the parent method before adding our changes.

From the previous post we added this method to our Database class.


public Task> GetPropertiesAsync()
{
    return database.Table().ToListAsync();
}

We use this to set the ItemSource of the ListView to be all of our Properties in the database.

The next thing we want to add is a click event listener so that when a ListView Item is clicked, it will go to the edit page for that Property and pass its database ID to allow it to be edited.

Xamarin Forms Entry

I am rewriting the Cashflow calculator app that I made last fall from Java to a Xamarin Forms app. If I ever decide to release to iOS this will make it much easier.

One of the workhorses for this app is the Entry form element. This is your standard input field from the keyboard.

There are two features that I want to talk about today. Setting the keyboard type and Completed and TextChanged events.

Setting the Keyboard

The Entry element lets you specify the keyboard type like you would expect. There is the Default – the standard keyboard on your device, Numeric – number only entry for things like calculators and money (the one I am using the most), also Telephone, Url, Email, and Chat.

If you have done any sort of UI programming before, you know that limiting the characters that your user can put in significantly reduces the number of potential errors.

XAML Example:


<Entry Keyboard="Numeric" />

The Completed Event

Whenever the user finishes filling out the field and hits the enter or next key, the Completed event gets fired. You can hook up your Entry field to call a function whenever this happens.

For me whenever the user changes one of the values in my form, I recalculate the cashflow value of the property they are putting in. This way they get instant feedback on what one value has to the overall calculation.

XAML Example:


<Entry Completed="CalculateCashflow" />

Where CalculateCashflow is a function in the XAML’s code behind file.

TextChanged Event

This allows you to call a function as soon as the text in a field gets changed, not just when you are done changing it. It might seem like an odd thing to have since we already have a Completed event, but I will give you an instance I plan on using it for.

A couple of my form fields will be connected and be different representations of the same value. For instance, when estimating cashflow of a property it is common to estimate the repair and vacancy costs as percents of the rent.

In this case I will have a pair of split fields that are related. A repair_cash Entry and a repair_percent Entry. Whenever one of them changes, I want the other one to be updated.

XAML Example:


<Entry x:Name="repair_cash" TextChanged="SetRepairPercent" />
<Entry x:Name="repair_percent" TextChanged="SetRepairCash" />

Where SetRepairPercent and SetRepairCash are functions in the XAML’s code behind file.

Note that the Completed event callback function takes a sender object and an EventArgs object while the TextChanged event callback function takes a sender object and a TextChangedEventArgs object.

Really enjoying Xamarin so far. Looking forward to releasing a couple apps with it this year.