question

Andreas-7809 avatar image
0 Votes"
Andreas-7809 asked Andreas-7809 answered

Xamarin: DataTemplateSelector and Compiled Bindings

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 ?} ".../>?




dotnet-xamarinforms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Andreas-7809 avatar image
0 Votes"
Andreas-7809 answered

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 :)

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.