Xamarin: DataTemplateSelector and Compiled Bindings

Andreas 96 Reputation points
2021-03-27T10:45:47.313+00:00

Hello,

I'm using compiled binding on my MainPage.

<ContentPage.BindingContext>
        <viewmodels:MainPageViewModel x:DataType="viewmodels:MainPageViewModel"/>
    </ContentPage.BindingContext>

For a ListView I added a DataTemplateSelector in the ContentPage.Resources section.

<ContentPage.Resources>

        <DataTemplate x:Key="headingTemplate">
            <ViewCell x:DataType="viewmodels:MainPageViewModel" BindableLayout.ItemsSource="{Binding Items}">
                <Label Text="{Binding ?} " BackgroundColor="Yellow"/>
            </ViewCell>
        </DataTemplate>

        <DataTemplate x:Key="notEditableTemplate">
            <ViewCell x:DataType="viewmodels:MainPageViewModel" BindableLayout.ItemsSource="{Binding Items}">
                <Label Text="{Binding ?}" BackgroundColor="Green"/>
            </ViewCell>
        </DataTemplate>

        <helpers:MainPageDataTemplateSelector x:Key="DataTemplateSelector"
                                                       HeadingTemplate="{StaticResource headingTemplate}"
                                                       NotEditableTemplate="{StaticResource notEditableTemplate}"/>

    </ContentPage.Resources>

The ListView consumes the DataTemplateSelector as followed.

<ListView BackgroundColor="White"
              ItemsSource="{Binding Items}"
              ItemTemplate="{StaticResource DataTemplateSelector}"/>

My question is, how can I bind the Text-Property of the label in the ContentPage.Resources section, where I added <Label Text="{Binding ?} ".../>?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas 96 Reputation points
    2021-03-28T13:21:00.817+00:00

    Okay, I found my bug. This question can be closed.

    I came up with this question because the property names of the underlying collection were not suggested in XAML plus the UI did not react as I expected.

    The bug was, that in the DataTemplateSelector there is an If-Statement that decides wether an item represents a 'heading' or not.
    In the viewmodel I added the heading-property to the model for the local database, but not to the ObservableCollection that is used to display the items on the UI. That's it...sometimes it can be that simple :)

    0 comments No comments

0 additional answers

Sort by: Most helpful