0
votes

I am implementing Azure B2C with Xamarin Forms and I want to implement some of the tutorials that azure have published except using the MVVM architecture that Prism provides.

I Don't mind the Xamarin Forms framework I just prefer prisms navigation, PageDialog and event features.

My issue is I am having a hard time migrating the code from the View Code behind to the Prism ViewModel.

One idea I thought about was if there was a way to use the view model we have already referenced in the xaml definition in the code behind, then we could call the relevant commands for navigation while still leveraging the Sample code in the code behind.

However I am fairly new to the framework and I suspect that this approach may not be the best for the situation.

Heres an example of what I am trying to describe: We have the OnAppearing method from the code behind and rather than using the Forms Navigation I wish to use the InaviagtionService from the view model

protected override async void OnAppearing()
    {
        try
        {
            PublicClientApplication publicClientApplication = new PublicClientApplication(AuthParameters.Authority, AuthParameters.ClientId);
            var authResult = await publicClientApplication.AcquireTokenSilentAsync(AuthParameters.Scopes, "", AuthParameters.Authority, AuthParameters.Policy, false);

            await Navigation.PushAsync(new MainPage());

        }
        catch
        {

        }
    }

rather than using this:

await Navigation.PushAsync(new MainPage());

something like this instead:

await Viewmodel._navigationService.NavigateAsync("MainPage");

Thanks for for reading :)

1

1 Answers

1
votes

Well first of all you need to expose a public method in the ViewModel that would calll the navigationService for you

let it be like

public async Task NavigateToMainAsync
{
    await _navigationService.NavigateAsync("MainPage");
}

The next step is to expose your ViewModel in the code behind, you can do that from the constructor in the code behind. The keyword here is BindingContext

private readonly MyPageViewModel _viewModel;
public MyPage()
{
  InitializeComponent();
  _viewModel = (MyPageViewModel)BindingContext;
}

And then you can use the _viewModel as you want. I would not expose the navigationService itself because I just think it would be ugly