Search code examples
.net-coremaui

.NET MAUI, hidding a collectionview when data is not available and showing it when it is available


I am implementing an ecommerce mobile app in .NET Maui. I have Trending-collectionviews and bestselling-collectionview. I would like to add a collectionview that will hold new products-Collectionview and subsequently hide it when its not there in the HomePage. How can I achieve this


Solution

  • This solution will Hide/Show CollectionView, based on the List property has any items in it or not using the Converter.

    You can create a Converter which returns true if there are items, False otherwise. Suppose you name this converter as IsListHasItemsConverter

    public class IsListHasItemsConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(value is IEnumerable<object> source) ? (object) false : (object) source.Any<object>();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Then in your Xaml, reference this converter into page's Resources. Ex:

    <ContentPage.Resources>
        <converters:IsListHasItemsConverter x:Key="IsListHasItemsConverter" />
    </ContentPage.Resources>
    

    And then in your CollectionView

    <CollectionView
         IsVisible="{Binding MyProducts, Converter={StaticResource IsListHasItemsConverter}}"
    

    NOTE: After Add/Remove item from the MyPrpducts, if this is not updating then try to RaisePropertyChanged to notify UI to invoke this converter in such events.