views:

71

answers:

2

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).

A: 

Maybe XamlReader.Load() will do the trick? I'm saying maybe, because I haven't tested it. But according to MSDN it looks like what you need...

Update: Now this answer is irrelevant. Haven't got initial idea :).

Anvaka
+5  A: 

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);
AnthonyWJones
Brilliant answer, Anthony! +1 from me. Cheers.
Anvaka
Works great... just had to add my Views Namespace .GetType("SilverlightApplication1.Views." + pageName);
Grayson Mitchell
+1 Good answer.
Henrik Söderlund