Prism学习笔记(二):我的第一个Prism程序HelloWorld
最近学习Prism框架(本文参考 我和未来有个约会 建立可扩展的Silverlight应用框架),下面是我第一个程序:
(一)新建项目PrismDemo
(1)将MainPage.xaml和MainPage.xaml.cs重新命名改为Shell.xaml和Shell.xaml.cs.
(2)在Shell.xaml中添加命名空间:
xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism"
(3)在Shell.xaml文件中添加如下代码:
<ItemsControl Name="MainRegion" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
(二)新建Silverlight应用程序项目HelloWordModule
(1)将其中的MainPage.xaml、MainPage.xaml.cs文件和App.xaml和App.xaml.cs文件
(2)添加View文件夹,并在View文件夹中添加用户控件HelloWorldView。
里面随意写上一句话,这里用TextBlock写了"Hello World"
(3)添加HelloWorldModule.cs 代码如下:
//添加命名空间
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
namespace HelloWordModule
{
public class HelloWorldModule:IModule
{
private readonly IRegionManager regionManager;
public HelloWorldModule(IRegionManager regionManager)
{
this.regionManager = regionManager;
}
public void Initialize()
{
regionManager.RegisterViewWithRegion("MainRegion", typeof(Views.HelloWorldView));
}
}
}
(三)在PrismDemo项目中添加Bootstrapper.cs,代码如下:
//添加命名空间
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.UnityExtensions;
using Microsoft.Practices.Unity;
using System.Windows;
namespace PrismDemo
{
public class Bootstrapper:UnityBootstrapper
{
protected override System.Windows.DependencyObject CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.RootVisual = (UIElement)this.Shell;
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWordModule.HelloWorldModule));
}
}
}
(四)在PrismDemo项目中的App.xaml.cs中Application_Startup改写为如下代码:
private void Application_Startup(object sender, StartupEventArgs e)
{
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
(五)项目最后结构如图:

浙公网安备 33010602011771号