New to Telerik UI for .NET MAUI? Start a free 30-day trial

Using ItemTemplateSelector with CollectionView for .NET MAUI

Environment

Version Product Author
11.0.0 Telerik UI for .NET MAUI CollectionView Dobrinka Yordanova

Description

I am migrating from RadListView to CollectionView for .NET MAUI. In RadListView, I used the RadListView.ItemTemplateSelector to dynamically select item templates at runtime. However, I could not find an equivalent feature for the CollectionView. How can I achieve dynamic item template selection in the CollectionView?

This knowledge base article also answers the following questions:

  • How to use ItemTemplateSelector in CollectionView for .NET MAUI?
  • How to dynamically select templates in CollectionView?
  • Implementing custom DataTemplateSelector for CollectionView?

Solution

To achieve dynamic item template selection in the CollectionView, you can use the DataTemplateSelector provided by .NET MAUI. The DataTemplateSelector enables you to define logic for choosing different templates based on item properties.

1. Create a custom template selector class that inherits from DataTemplateSelector. Override the OnSelectTemplate method to provide logic for selecting the appropriate template.

   using Microsoft.Maui.Controls;

   public class CustomTemplateSelector : DataTemplateSelector
   {
       public DataTemplate TemplateOne { get; set; }
       public DataTemplate TemplateTwo { get; set; }

       protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
       {
           var myItem = item as MyItemType;
           if (myItem != null && myItem.Condition)
           {
               return TemplateOne;
           }
           return TemplateTwo;
       }
   }

2. Declare the templates and the custom selector in your XAML file.

   <ResourceDictionary>
       <DataTemplate x:Key="TemplateOne">
           <Label Text="{Binding PropertyOne}" />
       </DataTemplate>
       <DataTemplate x:Key="TemplateTwo">
           <Label Text="{Binding PropertyTwo}" />
       </DataTemplate>

       <local:CustomTemplateSelector x:Key="CustomSelector" 
                                     TemplateOne="{StaticResource TemplateOne}" 
                                     TemplateTwo="{StaticResource TemplateTwo}" />
   </ResourceDictionary>

3. Set the ItemTemplate property of the CollectionView to the custom template selector.

<telerik:RadCollectionView ItemsSource="{Binding Items}" 
                                                 ItemTemplate="{StaticResource CustomSelector}" />

See Also

In this article