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

8ulbf1ek  于 2022-12-07  发布在  .NET
关注(0)|答案(1)|浏览(158)

.Net毛伊岛
我正在将一个对象传递给页面/视图模型,但它在构造函数中为null。我需要从中派生一些数据以传递回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");

        }
    }
}

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

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

此路由器已在APP Shell中注册
页面有我从一个教程中使用的代码(仍然是一个新手)

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

    protected override void OnNavigatedTo(NavigatedToEventArgs args) {
        base.OnNavigatedTo(args);
    }
}
axr492tv

axr492tv1#

在构造函数中,属性的值实际上总是null,因为在实际设置属性之前必须构造对象。(我自己刚刚学会了如何这样做!)
您需要对ObservableProperty为您生成的OnOpenJobChanged函数中更改的值做出响应(在您键入“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
    }
}

相关问题