首页 > 解决方案 > Xamarin.forms 如何将字符串转换为页面

问题描述

这是我在 ViewModel 中的代码

  async Task ExecuteMenu(object obj)
        {
            Page page = new Page();
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            Type t_form = asm.GetType(asm.GetName().FullName + "." + obj.ToString());
            page = Activator.CreateInstance(t_form) as Page;


            try
            {
                await Application.Current.MainPage.Navigation.PushAsync(new page());
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {

            }
        }

我有一个从命令加载的菜单元素。在 obj 中,我传递包含所选内容页名称的字符串。我不知道如何将字符串名称转换为页面对象名称。此代码不起作用。我正在尝试动态调用页面。

标签: xamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


尝试这个:

         var pageType= Type.GetType($"NamespaceOfYourView.{obj}");
         var page = Activator.CreateInstance(pageType) as Page;
         await Application.Current.MainPage.Navigation.PushAsync(page );

推荐阅读