Visual Studio 如何将查询参数传递给.Net Maui视图模型

gudnpqoy  于 2023-02-24  发布在  .NET
关注(0)|答案(1)|浏览(159)

在我的接收ViewModel中,我希望引用异步方法GetMovies()中的[QueryParameter]并运行它以使用Movies填充页面。我已在MovieListGenrePageViewModel中的GetMovies方法处放置断点。调用它时,selectedGenre为null,但它已在{Binding}中返回。我遗漏了什么?

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;
            }
        }
    }
}
pftdvrlh

pftdvrlh1#

您可以先检查以下部件:
1.检查参数SelectedGenre是否正确:

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

2.调试以查看代码SetProperty(ref selectedGenre, value);是否可以执行:

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

3.尝试添加函数GetMovies,如下所示:

private Genre selectedGenre;

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

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

相关问题