簡體   English   中英

.Net Maui/XAML QueryParameter 在 viewmodel 構造函數中是 NULL 但在 XAML 中可用,我如何在 viewmodel 中訪問它?

[英].Net Maui/XAML QueryParameter is NULL in the viewmodel Constructor but usable in XAML, how do I access it in the viewmodel?

.Net 毛伊島

我將 object 傳遞給頁面/視圖模型,但它在構造函數中是 null。 我需要從中派生一些數據以傳回 XAML 頁面,但我不知道它何時或如何在視圖模型中設置。

我相信這里使用的 [QueryProperty] 正在使用 MVVM 社區工具包在幕后發揮作用

[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,因為必須先構造 object,然后才能實際設置該屬性。 (我自己剛剛學會了如何做到這一點!)

您需要響應ObservableProperty為您生成的OnOpenJobChanged function 中的更改值(在您鍵入“部分”之后,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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM