Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...