0

I want to use Reflection to fill my Checkboxes dynamically.

I found an helping answer here

And used it in my Code:

    public static List<System.Type> getModuleList()
    {
        // fill with all Classes in Timestamp.View.UserControls.ModuleView per Reflection


        List<System.Type> theList = Assembly.GetExecutingAssembly().GetTypes()
                              .Where(t => t.Namespace == "Timestamp.View.UserControls.ModuleView")
                              .ToList();


        return theList;
    }

I filled my Checkboxes like:

   foreach (System.Type type in ModuleController.getModuleList())
        {
            cbModule1.Items.Add(type);
            cbModule2.Items.Add(type);
            cbModule3.Items.Add(type);
            cbModule4.Items.Add(type);
        }
  1. Now i want to create a new Instance of the SelectedType

      private void CbModule4_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ucModul4.Content = //new Instance of Selected Item
    }
    

I could use Reflection to create a new Instance, but I dont know how.

  1. I want to give every Class a String which will be shown as Item in the Checkbox. Is this possible, or do I need a Method to find a Class by its String?

EDIT: I need to argue why my question differs from this one

So first of all this question could only solve one of my Problems, but i found it earlier and it didn't helped me. I don't know how to get the type of the list and how i can give the class an alias.

Community
  • 1
  • 1
itskajo
  • 285
  • 2
  • 19
  • Don't go for reflection over namespaces, define a shared interface as they all seem to have something in common, and then just get the types that implement this interface. Then you can fill those properties you want in a typed way, and presumably they would have a label and a checked property – Icepickle Feb 23 '17 at 08:20
  • @Icepickle They all have a shared Interface called IModuleView. But how do i get all Classes implementing this Interface? – itskajo Feb 23 '17 at 08:22

1 Answers1

1

because adding Type to combobox makes type.ToString() and puts string representation into combobox, you can use

var instance = Activator.CreateInstance(Type.GetType(cbModule4.SelectedText))

When passing type, you can do:

var instance = Activator.CreateInstance(theList[0]))

Nino
  • 6,931
  • 2
  • 27
  • 42