Pages

Wednesday 27 October 2010

Converting WPF to XBAP (PRISM 2.2)

One day I had to make a conversion from WPF (PRISM 2.2) desktop application to XBAP application. Task which seems to be straightforward took me more time that I expected. I encountered some problems and I want to share all my conclusions and experiences.


My original approach in WPF desktop app (PRISM 2.2) is:
  1. No StartupUri attribute in App.xaml 
  2. Regions are defined in Shell.xaml e.g. cal:RegionManager.RegionName="{x:Static common:RegionNames.DocRegion}"
  3. App.xaml.cs / OnStartup creates and runs UnityBootstrapper
  4. UnityBootstrapper registers Modules, Types, creates ShellPresentationModel + Shell
Basically UnityBootstrapper is responsible for creating/instantiating the Shell.


WPF => XBAP conversion
Step 1.
Instead of using App.xaml.cs and

   1:     protected override void OnStartup(StartupEventArgs e) 
   2:     {
   3:        base.OnStartup(e);
   4:        UnityBootstrapper bootstrapper = new Bootstrapper();
   5:        bootstrapper.Run();
   6:     } 

 I had to use App.xaml and StartupUri="..." attribute.
Step 2.
I had to remove all my XAML region references cal:RegionManager.RegionName="..." and replace them with RegionManager.SetRegionName(..., ....). XBAP application (with StartupUri attribute) creates Shell before creating Bootstrapper, so at this stage application is not aware of existence of RegionManager.



   1:      public partial class Shell : Page, IShellView
   2:      {
   3:          public Shell()
   4:          {
   5:              Bootstrapper bootstrapper = new Bootstrapper(this);
   6:              InitializeComponent();
   7:              bootstrapper.Run();
   8:          }
   9:          
  10:          //...
  11:   
  12:      }

Step 3.
I had to populate the constructor of my Shell with Bootstrapper and pass Shell reference into Bootstrapper to make region registering process (step 2) possible.

   1:  public class Bootstrapper : UnityBootstrapper
   2:      {
   3:          private IShell shell;
   4:   
   5:          public Shell Shell
   6:          {
   7:              get { return shell as Shell; }
   8:          }
   9:   
  10:          public Bootstrapper(IShell shell)
  11:          {
  12:              shell = shell;
  13:          }
  14:   
  15:          //...
  16:   
  17:          protected override DependencyObject CreateShell()
  18:          {
  19:              ShellPresentationModel presenter = Container.Resolve<ShellPresentationModel>();
  20:              ShellView.Model = presenter;
  21:   
  22:              RegionManager.SetRegionName(ShellView.DocRegionControl,
  23:                  RegionNames.DocRegion);
  24:   
  25:              //...
  26:   
  27:              return ShellView;
  28:          }
  29:      } 

Useful links:

No comments:

Post a Comment