Advanced Databinding Part 3 – Null or Missing Values

You want to bind to a collection of values and display each in turn, but it is possible that some of the objects in the list have null properties, or some properties are missing altogether.

You can handle this with value converters, but there is a better (easier to write, easier to understand when reviewing) way.

In your Xaml, if you suspect a value may be null, you can makr it TargetNullValue and give it a string to display

TargetNullValue='Age unknown'

Similarly, if the value may be missing you can provide a default value,

FallbackValue='No School Found'

In this posting we’ll show how to use both.

To get started, we’ll need some objects to put in the list. Here are a person and a derived student objects (I put them in separate files in the Models folder):

public class Person
{
    public string Name { get; set; }
    public int? Age { get; set; }
}

public class Student : Person
{
    public string SchoolName { get; set; }
}

Next, I initialized a collection of these objects in a file named School which for debatable reasons I put in the ViewModel folder:

using System;
using System.Collections.Generic;
using System.Text;
using NullOrFallback.Model;

namespace NullOrFallback.ViewModel
{
    public class School
    {
        public List<Person> People { get; set; }

        public School()
        {
            try
            {
                var peeps = new List<Person>()
                {
                    new Person()
                    {
                        Name = "Marcel Proust",
                        Age = 55
                    },
                    new Person()
                    {
                        Name = "Maggie O'Farrell",
                        Age = null
                    },
                    new Student()
                    {
                        Name = "Richard Powers",
                        Age = 45,
                        SchoolName = "Harvard"
                    },
                    new Student()
                    {
                        Name = "James Joyce",
                        Age = 33,
                        SchoolName="Streets of Dublin"
                    },

                };
                People=peeps;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
         
        }
    }
}

I set the binding context in Main.xaml.cs

public MainPage()
{
    BindingContext=new School() ;
    InitializeComponent();
}

And now the fun part. In my Xaml I create three labels. The first is simple, the second handles the case where age may be null, and the third handles the case where there may not be a school name:

<ListView HasUnevenRows="True" ItemsSource="{Binding People}">
	<ListView.ItemTemplate>
		<DataTemplate>
			<ViewCell>
				<Grid RowDefinitions="Auto,Auto,Auto,Auto" Margin="5">
					<Label Grid.Row="0" 
						Text="{Binding Name}" />
					<Label Grid.Row="1" 
						Text="{Binding Age, 
						TargetNullValue='Age unknown'}" />
					<Label Grid.Row="2" 
						Text="{Binding SchoolName, 
						FallbackValue='No School Found'}" />
					<BoxView
						Grid.Row="3"
						HeightRequest="1"
						Color="Black" />
				</Grid>
			</ViewCell>
		</DataTemplate>
	</ListView.ItemTemplate>
</ListView>

The net effect is to provide a much cleaner output of the values:

Notice that for our first entry (Proust) no school was found, and for our second entry, Maggie O’Farrell, no age nor school was found. (NB: I made up the ages and schools!)

Find the beginning of this series here

More (from Microsoft) on this topic here

Source code here

These blog posts are written by Jesse Liberty and Rodrigo Juarez.

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.

Rodrigo Juarez is a full-stack and Xamarin Certified Mobile Professional developer. His mission is to solve complex problems for his clients focusing on the results, applying the most adequate technology available and best practices to ensure a cost-effective and high-quality solution. He has 20+ years of experience in a wide variety of projects in the development of applications for web, desktop and mobile using Microsoft technologies in areas such as management, services, insurance, pharmacy and banks.  He can be reached at  Rodrigo Juarez

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.