Home > Back-end >  TargetNullValue not working in ListView in Xamarin app
TargetNullValue not working in ListView in Xamarin app

Time:03-11

I'm trying to display some text -- or an image -- if there's no data for my ListView to display in my Xamarin Forms 5 app but I can't get it to work.

Here's what my ListView looks like:

<ListView
   x:Name="CustomersList"
   ItemsSource="{Binding Customers, TargetNullValue='No customers!'}"
   BackgroundColor="Transparent">
      <ListView.ItemTemplate>
          <DataTemplate>
              <TextCell
                 Text="{Binding FullName}"
                 TextColor="{StaticResource PrimaryDark}"
                 Command="{Binding Source={x:Reference Name=CustomersList}, Path=BindingContext.CustomerSelectedCommand}"
                 CommandParameter="{Binding .}"/>
          </DataTemplate>
      </ListView.ItemTemplate>
</ListView>

The source for the ListView is set as follows in my ViewModel

ObservableRangeCollection<CustomerModel> customers;
public ObservableRangeCollection<CustomerModel> Customers
{
   get => customers;
   set
   {
      if (customers == value)
         return;

      customers = value;
      OnPropertyChanged();
   }
}

If my API call returns nothing, I do a Customers = null;

When I use TargetNullValue as shown above, I acutally get errors where I bind the TextCell to FullName. It shows:

'FullName' property not found on 'N', target property: 'Xamarin.Forms.TextCell.Text'

It then repeats this error message for every character in No Customers!.

I then tried using FallbackValue. This time I don't get an error but it simply doesn't show the "No Customers!" message.

How do I handle a ListView having no data to show? At the very least, I'd like to show some simple text message but it would be even better to show something nicer, maybe an image.

CodePudding user response:

If you are ok to switch from ListView to CollectionView, you can use the built-in CollectionView.EmptyView:

<CollectionView ItemsSource="{Binding Customers}"
                EmptyView="No customers!" ... />

With the same EmptyView you can define whatever view:

<CollectionView>
    <CollectionView.EmptyView>
        <ContentView>
           <image ... /> 
        </ContentView>
    </CollectionView.EmptyView>
</CollectionView>

Docs: CollectionView EmptyView

  • Related