silversunhunter
silversunhunter

Reputation: 1259

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

.Net Maui

I am passing an object to a page/viewmodel but it is null in the constructor. I need to derive some data from it to pass back to the XAML page but I don't know when or how it gets set in the viewmodel.

I believe the [QueryProperty] used here is doing some magic behind the scenes using 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");

        }
    }
}

In the page that navigates to this one i have this ICommand that is triggered on button click

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

This rout is registered in the APP Shell

The Page has this code I use from a tutorial (still a noob)

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

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

Upvotes: 3

Views: 3112

Answers (1)

Ian Bailey-Mortimer
Ian Bailey-Mortimer

Reputation: 345

The value of the property is indeed always null in the constructor, because the object has to be constructed before the property can actually be set. (I have just learnt how to do this myself!)

You need to respond to the changed value in the OnOpenJobChanged function that ObservableProperty generates for you (after you type "partial " VS should suggest the completion for you).

[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
    }
}

Upvotes: 8

Related Questions