Grayson Mitchell
Grayson Mitchell

Reputation: 1187

Silverlight: How to create a page dynamically

Problem: I store the page name I want opened in Silverlight in a database. When I startup the application I want to set the page to this string

so rather than this:

this.RootVisual = new MainPage();

I want something like this

string pageName = getValueFromDatabase()
if (!PageExists(pageName))
   throw error
else
   this.RootVisual = SomeWizzyMethodToCreatePage(pageName) 

I guess I will need to use reflection here to find all of the pages (PageExists), and then somehow create a new instance (SomeWizzyMethodToCreatePage).

Upvotes: 2

Views: 687

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189555

Assuming you mean the you aquire from the DB the name of the page that you want to determine the name of the page to display.

I'll take the simplest example where all the pages are in a single application assembly and a single known namespace. It can be as simple as this:-

Type pageType = Assembly.GetExecutingAssembly().GetType("SilverlightApplication1." + pageName);
RootVisual = (UIElement)Activator.CreateInstance(pageType);

Perhaps a more flexibable approach would be to store in the database an AssemblyQualifiedName. That way the page can be in a different assembly and/or namespace, it need only be present in the XAP (I'm not sure whether it can be in a cached assembly library zip). If the page name is an AssemblyQualifiedName then the code becomes:-

Type pageType = Type.GetType(pageName);
RootVisual = (UIElement)Activator.CreateInstance(pageType);

Upvotes: 6

Related Questions