如何将查询参数传递给.Net Maui ViewModel

问题描述 投票:0回答:2

在我的接收视图模型中,我想在异步方法 GetMovies() 中引用 [QueryParameter] 并运行它以用电影填充页面。我已将断点放置在 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;
            }
        }
    }
}

c# .net visual-studio mvvm maui
2个回答
6
投票

您可以先检查以下部分:

1.检查参数

SelectedGenre
是否正确:

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

2.debug 看看代码

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

0
投票

您可以使用 MVVM 工具包来做同样的事情。

[ObservableProperty]
private string? name;

partial void OnNameChanging(string? value)
{
    Console.WriteLine($"Name is about to change to {value}");
}

partial void OnNameChanged(string? value)
{
    Console.WriteLine($"Name has changed to {value}");
}

文档链接

© www.soinside.com 2019 - 2024. All rights reserved.