1

Given I have about 100 classes in my Prism application project, a project can become difficult to debug for other devs. I am looking for a way to show a toast when a user navigates to any page. This toast message will tell the user the respective view model page title of the current view.

public class AViewModel 
{
   public override void OnNavigatingTo(INavigationParameters parameters)
   {
      Toast("AViewModel")
   }
}

public class BViewModel 
{
    public override void OnNavigatingTo(INavigationParameters parameters)
    {
        Toast("BViewModel")
    }
}

public class CViewModel 
{
   public override void OnNavigatingTo(INavigationParameters parameters)
   {
      Toast("CViewModel")
   }
}

public class DViewModel 
{
   public override void OnNavigatingTo(INavigationParameters parameters)
   {
      Toast("DViewModel")
   }
}

Im looking to achieve such functionality without actually including Toast("ViewModelName") in every class. Is there a way I can override something and implement this?

tendai
  • 1,172
  • 1
  • 11
  • 22

1 Answers1

0

It is easy to achieve in few steps like below

  1. Create a BaseViewModel class

    public class BaseViewModel : INavigationAware
     {
         string PageName { get; set; }
         public BaseViewModel(string pageName)
         {
             PageName = pageName;
         }
         public virtual void OnNavigatedFrom(INavigationParameters parameters)
         {
           //Methods gets called when current active page navigated to some other page
         }
    
     public virtual void OnNavigatedTo(INavigationParameters parameters)
     {
       //Methods gets called when current page is activated
    
       //System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1);
       //Toast(stackFrame.GetMethod().DeclaringType.Name);
    
       Toast(PageName);
     }
    }
    
  2. Inherit BaseViewModel class for each of ur ViewModel class

    public class AViewModel : BaseViewModel {
      //Constructor
      public AViewModel() : base(nameof(AViewModel))
      {
         //Some code
      }
    
//MethodA
public void MethodA()
{
    //Some code
} }

Note:-

base(nameof(AViewModel))

I hope this will help

tendai
  • 1,172
  • 1
  • 11
  • 22
Hamid Shaikh
  • 197
  • 6
  • Thank you for the response. It does work but was trying to eliminating having to add a parameter into every ViewModel. – tendai Jul 30 '20 at 09:24