How to load detailpage once in Xamarin Forms MasterDetailPage project

不问归期 提交于 2020-06-18 12:52:32

问题


I noticed detailpage is loaded from scratch everytime masterpage menu item is selected (so its constructor is called everytime). Is there a way to implement a detailpage which is loaded once, so everytime menu item is selected detailpage is simply showed/not showed?

Thanks, Lewix


回答1:


I solved implementing a dictionary page cache in MasterDetailPage:

// in constructor
MasterPageMenuCache = new Dictionary<Type, Page>(); 

// in OnItemSelected
if (MasterPageMenuCache.Count == 0)
    MasterPageMenuCache.Add(typeof(FirstDefaultDetailPage), Detail);

var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
    if (MasterPageMenuCache.ContainsKey(item.TargetType))
    {
        Detail = MasterPageMenuCache[item.TargetType];
    }
    else
    {
        Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
        MasterPageMenuCache.Add(item.TargetType, Detail);
    }

    masterPage.ListView.SelectedItem = null;
    IsPresented = false;
}



回答2:


Yes you can cache the Pages.

Here is an example with a dictionary which stores the pages.

public partial class MyMasterDetailPage : MasterDetailPage
{

    public MyMasterDetailPage()
    {
        Pages = new Dictionary<MenuType, Page>();
    }

    public enum MenuType
    {
        Home,
        Settings,
        Map
    }
    private Dictionary<MenuType, Page> Pages { get; set; }
    public async Task NavigateAsync(MenuType id)
    {
        Page newPage;
        if (!Pages.ContainsKey(id)) // check the page is already in the dictionary
        { 
            Page page;
            switch (id)
            {
                case MenuType.Home:
                    page = new ContentPage()
                    {
                        Title = "Home",
                    };
                    Pages.Add(id, page);
                    break;

                case MenuType.Map:
                    page = new ContentPage()
                    {
                        Title = "Map",
                    };

                    Pages.Add(id, page);
                    break;

                case MenuType.Settings:
                    page = new ContentPage()
                    {
                        Title = "Settings",
                    };

                    Pages.Add(id, page);
                    break;
            }
        }

        newPage = Pages[id];
        if (newPage == null)
            return;

        Detail = newPage; // assign the page
    }
}


来源:https://stackoverflow.com/questions/37212632/how-to-load-detailpage-once-in-xamarin-forms-masterdetailpage-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!