4

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

Since I don't know the total number of pages, I have to load each page at runtime using the Dynamic keyword. My code is as follows as is working perfectly:

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

My problem is that I've just learned that the app must be Silverlight 3 and, as a result, it will not be able to use the dynamic type. I've tried changing "dynamic" to "object" but I need to be able to access the XAML on each page and manipulate the XAML. If all I needed was to access properties and methods, I'd be able to follow the solution for creating dynamic objects here.

How can I dynamically create each page and still be able to access the XAML?

Community
  • 1
  • 1
  • 2
    The first answer is correct, but it sounds like your site should be data driven instead. A contrived page numbering system usually indicates a design problem. If you let us know more about the actual business problem you are trying to solve, we might be able to offer a better solution. Cheers – iCollect.it Ltd Aug 30 '10 at 21:46
  • The page numbering system certainly is contrived but, in this situation, it is very much by design. The pages are generated from a Microsoft Word document and then inserted into a Silverlight app and can change at any time. In this case, the page numbers do make a lot of sense. Regardless, in this specific situation, the "pages" will live only in a static Silverlight app that will let users scroll through the content. The numbering system doesn't matter so long as it is consequential. –  Aug 30 '10 at 22:07

1 Answers1

1

I'm assuming that each page is a UserControl. If this is the case then you're pretty much already there. Instead of creating dynamic objects, create a bunch of UserControl objects.

Change your code to this:

Type type = Type.GetType("Pages.Page_" + (index).ToString(), true);
UserControl newPage = (UserControl)Activator.CreateInstance(type);
NakedBrunch
  • 48,713
  • 13
  • 73
  • 98