Divakar
Divakar

Reputation: 544

OnNavigatedTo() method is not triggered in Xamarin.Forms

I have inherited my view model class from INavigateAware interface as below,

public class ViewModel : INavigationAware
{
    public ViewModel()
    {

    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

    public void OnNavigatedTo(NavigationParameters parameters)
    {
        // some codes
    }

}

And called that view model in the associated view(the page I have been navigated to)

public partial class Page1 : ContentPage
{
    ViewModel viewModel;
    public Page1()
    {
        InitializeComponent();
        viewModel = new ViewModel();
        this.Content = myview; //myview is my control like grid
    }
}

Now my problem is when I navigate to this page(Page1), OnNavigateTo() method in ViewModel is not triggered. Please someone helps me how to make trigger OnNavigateTo() method.

Thanks in advance.

Upvotes: 1

Views: 3240

Answers (1)

Artem Zelinskiy
Artem Zelinskiy

Reputation: 2210

First thing first, check if you have AutowireViewModel parameter in your page class set to True.

Second, you should not assign view model yourself, prism will do that for you, when you call PushViewModel

Third there is well known limitation in prism: https://github.com/PrismLibrary/Prism/issues/563

There is also workaround suggested:

Create interface:

public interface IPageNavigationAware
{
    void OnAppearing();
    void OnDisappearing();
}

Derive your ViewModel class from this interface. In the Views code behind:

protected override void OnAppearing()
{
    (BindingContext as IPageNavigationAware)?.OnAppearing();
}

protected override void OnDisappearing()
{
    (BindingContext as IPageNavigationAware)?.OnDisappearing();
}

The problem with that is that OnAppearing/OnDissapparing are not reliable navigation methods and do not accept parameters, but rather page lifecycle methods. They do not indicate when a page has been navigated to or from. You can have instances where a parent page can be appearing at the same time as multiple child pages are appearing. This will be addressed when Xamarin provides a proper navigation API.

Upvotes: 1

Related Questions