Search code examples
c#xamarinxamarin.formsmaster-detailfreshmvvm

Xamarin Forms: MasterPage Helper class


My current app has multiple master detail pages. I want to create a helper class which has a function that accepts list of PageModels-Pages( ViewModels-views ) which I can iterate through and create master detail pages.

MyCurrent Code:

public static Page SetupMasterDetailNav<T,U>( Dictionary<T,string> Menu) 
        where T : class 
         //In Dictionary T is ViewModel(PageModel) , 
          String is name displayed on Master page  
    {
        var masterDetail = new FreshMasterDetailNavigationContainer();

        foreach (KeyValuePair<T,string> item in Menu)
        {
            masterDetail.AddPage<item.Key>(item.Value); 
        }
        masterDetail.Init("");
        return masterDetail;
    }

This code doesn't work.It tells me item.key is a variable and cannot be used as a type Can any one suggest me a better approach or how else I can achieve my goal ?


Solution

  • The AddPage<T> method is a generic method, which expects a type. In this case it is FreshBasePageModel. The normal usage would be something like:

    masterDetail.AddPage<MyViewModel>("MyPage", model);
    

    or:

    masterDetail.AddPage<MyViewModel>("MyPage");
    

    Since your method is already generic, and seems you want it to be the type of the ViewModel you could simply do:

    masterDetail.AddPage<T>(item.Value);
    

    To do this you must change the your method signature to something like:

    public static Page SetupMasterDetailNav<T,U>(Dictionary<T,string> Menu) 
        where T : FreshBasePageModel
    

    Not sure what the U is used for in your case, you haven't shown usage of it.

    Why are you even doing this is puzzling me.