I'm building a podcast player using Maui targeting Android using the Maui and Mvvm community tookits.
I've got a page with a CollectionView
defined like this:
<CollectionView
x:Name="PodcastsListView"
ItemsSource="{Binding Podcasts}"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectPodcastCommand}"
SelectionChangedCommandParameter="{Binding SelectedItem, Source={RelativeSource Self}}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="vm:PodcastViewModel">
<HorizontalStackLayout Padding="10">
<Image
Source="{Binding ImageSource}"
HeightRequest="50"
WidthRequest="50"
Aspect="AspectFill" />
<VerticalStackLayout>
<Label
Text="{Binding Podcast.Title}"
VerticalOptions="Center"
Margin="10,0,0,0" />
<Label
Text="{Binding Podcast.Description}"
VerticalOptions="Center"
Margin="10,0,0,0" />
</VerticalStackLayout>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
The relevant parts of the view model are:
public partial class PodcastsViewModel : ObservableObject
{
public PodcastsViewModel(IRepository<Podcast> repository, IPodcastRetriever podcastRetriever)
{
Podcasts = [.. repository.GetAll().Select(p => new PodcastViewModel(p))];
}
public ObservableCollection<PodcastViewModel> Podcasts { get; }
[RelayCommand]
private async Task LoadPodcastAsync()
{
// code to load a feed from a URL input and add it
// to the Podcasts collection. This bit works.
}
[RelayCommand]
private async Task SelectPodcastAsync(PodcastViewModel podcast)
{
if (podcast is not null)
{
await PodcastPage.GoToAsync(podcast.Podcast.Id);
}
}
}
When I run the app in the Android 14 emulator from Visual Studio, I can load a feed from a URL. It gets added to the collection and appears correctly on the page. I can tap the item in the list and the PodcastsViewModel.SelectPodcastAsync
method gets called, but the podcast
parameter is null
.
How do I fix the binding so the selected item is passed to the method? This actually worked before I update my project to .Net 9.0.