Rajzer
Rajzer

Reputation: 1296

Xamarin.forms how to convert string to Page

This is my code in the 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
            {

            }
        }

I have a menu elements loading from Command. In obj i pass string who contains the name of the selected contentpage. I dont know how to convert string name into page object name . This code doesn't work. I'm trying to dynamically call pages.

Upvotes: 0

Views: 890

Answers (2)

Tuğçe Arar
Tuğçe Arar

Reputation: 806

Try this:

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

Upvotes: 3

ColeX
ColeX

Reputation: 14475

Replace asm.GetName().Name with asm.GetName().FullName ;

Output

GetName().Name : "yournamespace"

GetName().FullName : "yournamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

Obviously , Name string is the correct one .

Upvotes: 0

Related Questions