ish1104
ish1104

Reputation: 421

Need to overide the navigation method

I am using autofac for dependency injection and I need to override the navigation function. in order to do that I did

Locator.cs(where contain the Cs files)

         private readonly ContainerBuilder _builder;

    public locator()
    {
        _builder = new ContainerBuilder();
        register();
        Container = _builder.Build();
    }

    public IContainer Container { get; set; }

    private void register()
    {
        _builder.RegisterType<vm>().As<Ivm>();
        _builder.RegisterType<Vm1>();
        _builder.RegisterType < basevm>();

        _builder.RegisterType<MainPage>();
        _builder.RegisterType<xa>();
    }

In my app.Xaml.cs

In constructor

   public App()
    {
        InitializeComponent();
        locator locator1 = new locator();
        Container = locator1.Container;

        MainPage = new NavigationPage(Container.Resolve<MainPage>());
    }
    public static IContainer Container;

then I tried to override the navigation func in my main page code behind it cannot be override. what I am missing and where i use this

    public abstract void Navigate(SelectedItemChangedEventArgs e);

    public override async void Navigate(SelectedItemChangedEventArgs e)
    {
        xa patientListViewPage = App.Container.Resolve<xa>();

        await Navigation.PushAsync(patientListViewPage);
    }

why this is not working. I occur this error

'MainPage.Navigate(SelectedItemChangedEventArgs)': no suitable method found to override

Upvotes: 1

Views: 123

Answers (2)

Ishara Lakshitha
Ishara Lakshitha

Reputation: 176

I Can think of a better way You are using Autofac so you can have a generic method that can help the cause.

   public static async Task NavigateAsync<TContentPage>(INavigation navigation ) where TContentPage : ContentPage
    {
        var contentPage = App.Container.Resolve<TContentPage>();          

        await navigation.PushAsync(contentPage, true);
    }

Also If you need to pass a parameter You can modify it like this

        public static async Task NavigateAsync<TContentPage, TNavigationParameter>(INavigation navigation,
        TNavigationParameter navParam,
        Action<TContentPage, TNavigationParameter> action = null) where TContentPage : ContentPage
    {
        var contentPage = App.Container.Resolve<TContentPage>();          
        action?.Invoke(contentPage, navParam);           
        await navigation.PushAsync(contentPage, true);
    }

Upvotes: 1

Batuhan
Batuhan

Reputation: 1611

You can derive from NavigationPage reference.

public class CustomNavigationPage : NavigationPage
{
   //You can define your container here.
   public CustomNavigationPage()
   {
      //You can resolve here 
   }
}

and also you can look here

Upvotes: 1

Related Questions