.Net 毛伊岛
我正在将一个对象传递给页面/ View 模型,但它在构造函数中为空。我需要从中派生一些数据以传回 XAML 页面,但我不知道它何时或如何在 View 模型中设置。
我相信这里使用的 [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);
}
}
最佳答案
在构造函数中,属性的值确实始终为 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
}
}
关于c# - .Net Maui/XAML QueryParameter 在 View 模型构造函数中为 NULL,但在 XAML 中可用,如何在 View 模型中访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72757060/