0

In the Podcast sample app, I see that query parameters are received directly in view models -- as you can see here: https://github.com/microsoft/dotnet-podcasts/blob/main/src/Mobile/ViewModels/EpisodeDetailViewModel.cs

I tried this in my view model but I'm not getting any values i.e. null. I currently do it through code behind but I'd like to do it directly in the ViewModel.

Here's my current approach:

MyPage.xaml.cs

[QueryProperty(nameof(Id), nameof(Id))]
public partial class MyPage: ContentPage
{
   public string Id { get; set; }
   MyPageViewModel _vm;
   public MyPage(MyPageViewModel vm)
   {
       InitializeComponent();
       _vm = vm;
       BindingContext = _vm;
   }

   protected override void OnAppearing()
   {
      base.OnAppearing();
      _vm.InitAsync(Id);
   }
}

MyPageViewModel.cs

public partial class MyPageViewModel : BaseViewModel
{
   IMyService _myService;
   public MyPageViewModel(IMyService myService)
   {
      _myService = myService;
   }

   public async void InitAsync(string id)
   {
      // Get data
      var data = await _myService.Get(id);
   }
}

I'd like to simplify the approach and receive my query parameters directly in my view model.

How do I get my query parameters directly in my view model?

Sam
  • 26,817
  • 58
  • 206
  • 383
  • 1
    Does this answer your question? [how to pass query parameter to .Net Maui ViewModel](https://stackoverflow.com/questions/73293779/how-to-pass-query-parameter-to-net-maui-viewmodel) – Jason Apr 14 '23 at 19:49
  • Yes, this works but in the Podcast sample app, I don't see any backing fields or property setters. I'm trying to understand how they do it in the Podcast sample app. – Sam Apr 14 '23 at 20:23
  • that sample uses automatic properties – Jason Apr 14 '23 at 20:25
  • 2
    @Sam, query parameters have no place whatsoever in your Page logic. I suggest this: https://stackoverflow.com/a/75231231/6643940 – H.A.H. Apr 15 '23 at 10:08
  • @H.A.H. Didn't know about this one -- gotta read the docs! Definitely seems advantageous. Thank you! – Sam Apr 15 '23 at 19:20

0 Answers0