Silverlight:如何动态创建页面

Gra*_*ell 2 c# silverlight wpf

问题:我将要在Silverlight中打开的页面名称存储在数据库中.当我启动应用程序时,我想将页面设置为此字符串

所以不是这样的:

this.RootVisual = new MainPage();
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西

string pageName = getValueFromDatabase()
if (!PageExists(pageName))
   throw error
else
   this.RootVisual = SomeWizzyMethodToCreatePage(pageName) 
Run Code Online (Sandbox Code Playgroud)

我想我需要在这里使用反射来查找所有页面(PageExists),然后以某种方式创建一个新实例(SomeWizzyMethodToCreatePage).

Ant*_*nes 6

假设你的意思是,你从DB AQUIRE的名字,你要确定页面中显示的姓名的网页.

我将采用最简单的示例,其中所有页面都在单个应用程序程序集和单个已知名称空间中.它可以这么简单: -

Type pageType = Assembly.GetExecutingAssembly().GetType("SilverlightApplication1." + pageName);
RootVisual = (UIElement)Activator.CreateInstance(pageType);
Run Code Online (Sandbox Code Playgroud)

也许更灵活的方法是存储在数据库中AssemblyQualifiedName.这样页面可以在不同的程序集和/或命名空间中,它只需要存在于XAP中(我不确定它是否可以在缓存的程序集库zip中).如果页面名称是,AssemblyQualifiedName则代码变为: -

Type pageType = Type.GetType(pageName);
RootVisual = (UIElement)Activator.CreateInstance(pageType);
Run Code Online (Sandbox Code Playgroud)