Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dynamically generate view and view model based on class type

(Note: I am using Xamarin.Forms and the Rg.Plugins.Popup extension)

Suppose I have the following views:

MyView1.xaml
MyView2.xaml
MyView3.xaml

And I have their corresponding view models:

MyViewModel1.cs
MyViewModel2.cs
MyViewModel3.cs

I'd like a method in my navigation controller to show the view based on the type.

NavigationController.ShowView(typeof(MyView1));

or maybe

NavigationController.ShowView(typeof(MyView1), typeof(MyViewModel1));

How could I implement this?

Currently I am making a list:

{
    List<MyView> viewList = new List<MyView>();

    MyView1 view1 = new MyView1();
    MyViewModel1 viewModel1 = new MyViewModel1();
    view1.BindingContext = viewModel1;
    viewList.Add(view1);
    // etc ...
}

static public void ShowView(Type type) 
{
    foreach (MyView v in viewList) 
    {
        if (v.GetType() == type)
        {
            // code to show the view.
        }
    }
}

The problem I am having is that after showing the view, when it is dismissed, it is setting itself to null. So rather than pre-generate the views and storing them in a list, I'd like to generate new ones.

like image 492
jo phul Avatar asked Apr 08 '26 00:04

jo phul


1 Answers

quite easy...

public static View CreateView(Type vType, Type vmType)
{
    var view = (View)Activator.CreateInstance(vType);
    view.BindingContext = Activator.CreateInstance(vmType);
    return view;    
}
like image 127
Stephane Delcroix Avatar answered Apr 09 '26 14:04

Stephane Delcroix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!