Home > OS >  how to pass query parameter to .Net Maui ViewModel
how to pass query parameter to .Net Maui ViewModel

Time:08-13

In my receiving Viewmodel I want to reference the [QueryParameter] in my async method GetMovies() and run it to populate the page with Movies. I have placed the breakpoint at the GetMovies method in the MovieListGenrePageViewModel. When it is called, selectedGenre is null but it is been return in {Binding} . What am I missing?

using System.Collections.ObjectModel;
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using TimesNewsApp.Models;
using TimesNewsApp.Services;

namespace TimesNewsApp.ViewModels
{
    [QueryProperty(nameof(SelectedGenre), nameof(SelectedGenre))]
    public partial class MovieListGenrePageViewModel : BaseViewModel
    {
        public ObservableCollection<Result> Movie { get;} = new();


        private Genre selectedGenre;

        public Genre SelectedGenre
        {
            get => selectedGenre;
            set
            {
                SetProperty(ref selectedGenre, value);
            }
        }

        NewsApiManager apiService;

        public Command GetMovieComand { get; }

        public MovieListGenrePageViewModel(NewsApiManager apiService)
        {
            this.apiService = apiService;

            Task.Run(async () => await GetMovies(SelectedGenre));
            
        }


        async Task GetMovies(Genre SelectedGenre)
        {
            if (IsBusy)
                return;
            try
            {
                IsBusy = true;
                if (SelectedGenre == null)
                    return;
                
                Movie movies = await apiService.GetMovieByGenre(27);
                if (Movie.Count != 0)
                    return;
                foreach (var item in movies.results)
                    Movie.Add(item);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to get movie: {ex.Message}");
                await Application.Current.MainPage.DisplayAlert("Error!", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
    }
}

CodePudding user response:

You can check the following parts first:

1.check parameter SelectedGenre is correct:

 [QueryProperty(nameof(SelectedGenre), nameof(SelectedGenre))]

2.debug to see if code SetProperty(ref selectedGenre, value); can been executed:

public Genre SelectedGenre
    {
        get => selectedGenre;
        set
        {
            SetProperty(ref selectedGenre, value);
        }
    }

3.try to add function GetMovies as follows:

 private Genre selectedGenre;

    public Genre SelectedGenre
    {
        get => selectedGenre;
        set
        {
            SetProperty(ref selectedGenre, value);
            //add function GetMovies here

             Task.Run(async () => await GetMovies(value));
        }
    }
  • Related