In my .Net MAUI app, I have a viewmodel VideoChatPageModel that contains the following observable properties:
[ObservableProperty]
private LanguageViewModel _selectedLanguage;
[ObservableProperty]
private List<LanguageViewModel> _languages = new()
{
new LanguageViewModel { LanguageName = "English", FlagImage = "flag_united_kingdom.png", LanguageCode = "en" },
new LanguageViewModel { LanguageName = "Spanish", FlagImage = "flag_spain.png", LanguageCode = "es" },
new LanguageViewModel { LanguageName = "French", FlagImage = "flag_france.png", LanguageCode = "fr" }
};
Here is the LanguageViewModel class:
public class LanguageViewModel
{
public string LanguageName { get; set; }
public string LanguageCode { get;set; }
public string FlagImage { get; set; }
}
I have the following CollectionView on the page:
<CollectionView
Margin="5,5,5,15"
ItemSizingStrategy="MeasureAllItems"
ItemsSource="{Binding Languages}"
SelectedItem="{Binding SelectedLanguage, Mode=TwoWay}"
SelectionMode="Single">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView Padding="5" >
<Grid ColumnDefinitions="*,3*">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Image Source="{Binding FlagImage}" Grid.Column="0" HorizontalOptions="Start" />
<Label Text="{Binding LanguageName}" Grid.Column="1" HorizontalOptions="Start" />
</Grid>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
For some reason, it does not compile:
Error XFC0045 Binding: Property "FlagImage" not found on "Features.VideoChat.VideoChatPageModel".
It is clearly looking for the property not in the LanguageViewModel class, but in the VideoChatPageModel, which is the binding context for the whole page:
public VideoChatPage(VideoChatPageModel pageModel)
{
InitializeComponent();
BindingContext = pageModel;
}
But why does it behave so? If I replace the CollectionView with the following picker, it works:
<Picker ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}" ItemDisplayBinding="{Binding LanguageName}">
</Picker>
you need to add an
x:DataType
to theDataTemplate
so it knows what the type of itsBindingContext
is