Search code examples
c#mauicommunity-toolkit-mvvm

Clear selecteditem of collectionview from viewmodel when using Relay Command


I'm using CommunityToolkit MVVM for the first time. Here is my view called NewsPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="NewsApp.View.NewsPage"
         xmlns:viewmodel="clr-namespace:NewsApp.ViewModel"
         x:DataType="viewmodel:NewsViewModel"
         xmlns:model="clr-namespace:NewsApp.Model">
<CollectionView Margin="20"
                x:Name="cvNewsCollectionView"
                ItemsSource="{Binding NewsCollection}"
                SelectedItem="{Binding SelectedNews}"
                SelectionChangedCommand="{Binding GoToDetailsCommand}"                    
                SelectionMode="Single">
    <CollectionView.ItemsLayout>
        <LinearItemsLayout Orientation="Vertical"
                           ItemSpacing="20" />
    </CollectionView.ItemsLayout>
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="model:News">
            <VerticalStackLayout>
                <Image HeightRequest="200"
                       Aspect="AspectFill"
                       Source="{Binding ImageUrl }"/>
                <Label FontSize="Medium"
                       Text="{Binding Title}"/>
            </VerticalStackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

When an item is selected, it calls GoToDetails() from NewsViewModel. This correctly redirect to NewsDetailPage. But after redirection, I would like to clear selecteditem of cvNewsCollectionView. Can someone tell me how to do this? Here is the code from NewsViewModel.cs

namespace NewsApp.ViewModel
{
public partial class NewsViewModel : ObservableObject
{
    private MockNewsService _newsService;
    public ObservableCollection<News>   NewsCollection { get; set; } = new  ObservableCollection<News>();
    public NewsViewModel(MockNewsService newsService)
    {
        _newsService = newsService;
        GetNewsList();
    }

    private void GetNewsList()
    {
        var news = _newsService.GetNews();
        foreach (var item in news)
        {
            NewsCollection.Add(item);
        }
    }

    [ObservableProperty]
    News? selectedNews;

    [RelayCommand]
    void GoToDetails()
    {
        Shell.Current.GoToAsync($"{nameof(NewsDetailPage)}",
            new Dictionary<string, object>
            {
                { "randomkey", selectedNews }
            });               
    }
}
}

Solution

  • clear SelectedNews before navigating

    [RelayCommand]
    void GoToDetails()
    {
        var key = SelectedNews;
        SelectedNews = null;
    
        Shell.Current.GoToAsync($"{nameof(NewsDetailPage)}",
            new Dictionary<string, object>
            {
                { "randomkey", key }
            });               
    }