Hello,
x:DataType
is to use compiled bindings, and it means the VisualElement and its children will bind to this type of the object. Setting the CollectionView.ItemTemplate
property to a DataTemplateSelector
object means choose the appearance of each item in the CollectionView
at runtime.
Form your code snippets, you define two DataTemplate
in the ResourceDictionary of the Page, but you didn't define the item appearance in the CollectionView
by setting the CollectionView.ItemTemplate
. Defining both the data to display and its appearance is necessary for a CollectionView.
And you said "If I specify a named template in the ItemTemplate property it will work, but I would like to be able to have it pick the correct template based on Type." If so, it's recommended that you set the CollectionView.ItemTemplate
property to a DataTemplateSelector
object, it requires the use of a DataTemplateSelector
in the resources(the name can be DataTemplates
or others)
Please refer to the following code:
is
operator to check the type
public class ThingDataTemplateSelector : DataTemplateSelector
{
public DataTemplate ThingATemplate { get; set; }
public DataTemplate ThingBTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
return item is ThingA ? ThingATemplate : ThingBTemplate;
}
}
ResourceDictionary
<ContentPage.Resources>
<DataTemplate x:Key="ThingATemplate"... >
...
</DataTemplate>
<DataTemplate x:Key="ThingBTemplate"...>
...
</DataTemplate>
<vm:ThingDataTemplateSelector x:Key="ThingSelector"
ThingATemplate="{StaticResource ThingATemplate}"
ThingBTemplate="{StaticResource ThingBTemplate}" />
</ContentPage.Resources>
Populate the data and set item appearance
<CollectionView ItemsSource="{Binding BaseThingCollection}"
ItemTemplate="{StaticResource ThingSelector}">
</CollectionView>
For more details, you can see:
Compiled bindings - .NET MAUI | Microsoft Learn
Populate a CollectionView with Data - .NET MAUI | Microsoft Learn
Resource dictionaries - .NET MAUI | Microsoft Learn
Type-testing operators and cast expressions test the runtime type of an object | Microsoft Learn
Best Regards,
Wenyan Zhang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.