You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI:接收AppShell传递对象后在ViewModel执行指定方法

解决方案

因为QueryProperty的赋值是在ViewModel构造完成之后才执行的,所以在构造函数里调用RefreshCommand时,CourseSelected还未被赋值。利用CommunityToolkit.Mvvm的ObservableProperty特性,我们可以通过属性变更的partial方法来触发刷新操作:

在TopicSelectionViewModel中添加一个partial方法,该方法会在CourseSelected属性值发生变化时自动被调用:

[INotifyPropertyChanged]
[QueryProperty(nameof(CourseSelected), "courseSelected")]
public partial class TopicSelectionViewModel
{
    CancellationTokenSource cancellationTokenSource = new();
    [ObservableProperty]
    private Course courseSelected;
    public ObservableRangeCollection<Topic> Topics { get; set; } = new();

    [ObservableProperty]
    private bool isBusy;
    [ObservableProperty]
    private string title;
    [ObservableProperty]
    private string imageURL;

    // 添加属性变更触发的partial方法
    partial void OnCourseSelectedChanged(Course? oldValue, Course? newValue)
    {
        // 当成功接收Course对象后执行刷新命令
        if (newValue is not null)
        {
            _ = RefreshCommand.ExecuteAsync(null);
        }
    }

    [RelayCommand]
    async Task Refresh()
    {
        Topics.Clear();
        IsBusy = true;

        try
        {
            if (CourseSelected is not null)
            {
                Title = CourseSelected.Title;
                ImageURL = CourseSelected.ImageURL;

                if (CourseSelected.CourseRef.Equals("anat1"))
                {
                    foreach (Topic item in Constants.GetAnatomyTopics)
                    {
                        Topics.Add(item);
                    }
                }
                else if (CourseSelected.CourseRef.Equals("phys1"))
                {
                    foreach (Topic item in Constants.GetPhysiologyTopics)
                    {
                        Topics.Add(item);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            // 加载完成后重置忙碌状态
            IsBusy = false;
        }
    }
}

原理说明

标记了[ObservableProperty]的属性,CommunityToolkit.Mvvm会自动生成属性变更通知逻辑,同时允许我们定义名为On{PropertyName}Changed的partial方法——当属性值发生变化时,这个方法会被自动触发。我们在这里捕获CourseSelected的赋值完成事件,此时newValue就是传递过来的Course对象,直接调用RefreshCommand即可完成后续的数据加载。

内容的提问来源于stack exchange,提问作者Tanaka Mawere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:45:30