Reputation: 30334
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?
Upvotes: 0
Views: 1610
Reputation: 330
You may use MVVM toolkit Docs
[ObservableProperty]
private string? name;
partial void OnNameChanging(string? value)
{
Console.WriteLine($"Name is about to change to {value}");
}
partial void OnNameChanged(string? value)
{
Console.WriteLine($"Name has changed to {value}");
}
Upvotes: 0