Search code examples
xamlmvvmmaui

CollectionView not binding the properties in the data model without datatype


I created a collection view, but it is forcing me to use a datatype to say what the properties model is.

Previously it was not necessary to do this, did I do something wrong?

Without the datatype, the xaml does not find the property.

<ContentPage xmlns:models="clr-namespace:App.GRRInnovations.TodoManager.Models"
             xmlns:vm="clr-namespace:App.GRRInnovations.TodoManager.ViewModels"
             x:DataType="vm:TodayViewModel">

<CollectionView
                ItemsSource="{Binding Appointments}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:AppointmentModel">
            <HorizontalStackLayout>
                <Label FontAttributes="Bold" Text="{Binding Title}" />
                <Label Text=" - " />
                <Label Text="{Binding Description}" />
            </HorizontalStackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Binding is expected to occur without the need to use a datatype


Solution

  • From docs:

    To use compiled bindings, set an x:DataType attribute on a VisualElement to the type of the object that the VisualElement and its children will bind to. It's recommended to set the x:DataType attribute at the same level in the view hierarchy as the BindingContext is set. However, this attribute can be re-defined at any location in a view hierarchy.

    It is still not necessary to set datatype, you have choosed to use compiled bindings when you set x:DataType="vm:TodayViewModel" at your ContentPage level, and since the datatype for the CollectionView will be different than the one of the ContentPage then you had to specify it otherwise it will assume it is of the same type as it's parent (ContentPage) and will cause some errors such "properties not found".

    If you don't want to set the datatype at CollectionView level, then you have to remove the one in your ContentPage level, and of course you won't be using compiled bindings anymore.

    If you still get error of property not found:

    • Ensure that it is a public property.
    • Ensure that thre is no kind of typo in Appointments.Title Appointments.Description
    <ContentPage xmlns:models="clr-namespace:App.GRRInnovations.TodoManager.Models"
                 xmlns:vm="clr-namespace:App.GRRInnovations.TodoManager.ViewModels">
    
    <CollectionView
                    ItemsSource="{Binding Appointments}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <HorizontalStackLayout>
                    <Label FontAttributes="Bold" Text="{Binding Title}" />
                    <Label Text=" - " />
                    <Label Text="{Binding Description}" />
                </HorizontalStackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>