Dynamically create XAML objects

I have a Silverlight application that displays several "pages". Each page is a different XAML file with a different code. Pages are numbered sequentially as follows: page_1, page_2, page_3, ..., Page_n. Pages are not static and will be dynamically generated.

Since I do not know the total number of pages, I have to load each page at runtime using the Dynamic keyword. My code is as follows: it works fine:

Type type = Type.GetType("Pages.Page_" + (index).ToString(), true); dynamic newPage = Activator.CreateInstance(type); 

My problem is that I just found out that the application must be Silverlight 3, and as a result, it will not be able to use the dynamic type. I tried changing the β€œdynamic” to β€œobject”, but I need to have access to XAML on every page and manipulate XAML. If I needed to access properties and methods, I could follow the solution for creating dynamic objects here .

How can I dynamically create each page and still have access to XAML?

+4
source share
1 answer

I assume that each page is a UserControl. If so, then you are almost there. Instead of creating dynamic objects, create a bunch of UserControl objects.

Change the code as follows:

 Type type = Type.GetType("Pages.Page_" + (index).ToString(), true); UserControl newPage = (UserControl)Activator.CreateInstance(type); 
+1
source

All Articles