.Net Maui/XAML QueryParameter 在视图模型构造函数中为 NULL,但在 XAML 中可用,如何在视图模型中访问它?

sil*_*ter 2 .net c# xaml maui .net-maui

.Net 毛伊岛

我将一个对象传递给页面/视图模型,但它在构造函数中为空。我需要从中派生一些数据以传回 XAML 页面,但我不知道它何时或如何在视图模型中设置。

我相信这里使用的 [QueryProperty] 使用 MVVM Community Toolkit 在幕后发挥了一些作用

[QueryProperty("OpenJob", "OpenJob")]
public partial class NoteAvailabilityViewModel : BaseViewModel {
    
    [ObservableProperty]
    OpenJob openJob;

    public List<String> jobDates;

    public NoteAvailabilityViewModel(JobsService jobsService) {
        if (openJob == null) {
            Debug.Write("its null");

           //It's always null here
           //When, how is it set so I can access it in the viewmodel?

        }
        else {
            Debug.Write("its not null");

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在导航到此页面的页面中,我有一个在单击按钮时触发的 ICommand

[ICommand]
public static void NoteAvailabilityAsync(OpenJob openJob) {
    Shell.Current.GoToAsync($"{nameof(NoteAvailabilityPage)}", true, new Dictionary<string, object> {
            {"OpenJob", openJob }
    });
}
Run Code Online (Sandbox Code Playgroud)

该路由注册在APP Shell中

该页面有我在教程中使用的代码(仍然是菜鸟)

public partial class NoteAvailabilityPage : ContentPage {
    public NoteAvailabilityPage(ViewModel.NoteAvailabilityViewModel viewModel) {
        InitializeComponent();
        BindingContext = viewModel;
    }

    protected override void OnNavigatedTo(NavigatedToEventArgs args) {
        base.OnNavigatedTo(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

在构造函数中,属性的值确实始终为 null,因为必须先构造对象,然后才能实际设置属性。(我自己刚刚学会了如何做到这一点!)

您需要响应为您生成的OnOpenJobChanged函数中的更改值ObservableProperty(在您输入“partial”之后,VS 应建议您完成)。

[QueryProperty("OpenJob", "OpenJob")]
public partial class NoteAvailabilityViewModel : BaseViewModel {
    
    [ObservableProperty]
    OpenJob openJob;

    public List<String> jobDates;

    public NoteAvailabilityViewModel(JobsService jobsService) {
        // don't forget to save your jobsService here too :)
    }

    partial void OnOpenJobChanged(OpenJob value) {
        // process the query parameter value here
    }
}
Run Code Online (Sandbox Code Playgroud)