Compartir a través de


Using Prism to create a Windows Store app

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

From: Developing a Windows Store business app using C#, XAML, and Prism for the Windows Runtime

Previous page | Next page

Learn how to create a Windows Store business app using C#, Prism for the Windows Runtime, and Unity, and about the logical architecture of such an app. The article provides instructions on creating views, view models, model classes with validation support, adding items to the settings pane, and changing the conventions for naming and locating a view and a view model, and how to register a view model factory with views instead of using a dependency injection container.

Download

After you download the code, see Getting started using Prism for the Windows Runtime for instructions on how to compile and run the reference implementation, as well as understand the Microsoft Visual Studio solution structure.

You will learn

  • About the logical architecture of a Windows Store business app that uses Prism.
  • How to create a Windows Store app project using Prism and Unity.
  • How to create a view, view model, and model class with validation support using Prism.
  • How to add items to the Settings pane using Prism.
  • How to change the conventions used by Prism.

Applies to

  • Windows Runtime for Windows 8.1
  • C#
  • Extensible Application Markup Language (XAML)

This article describes the general steps a developer needs to perform to use Prism to accomplish different tasks. It is not meant to provide you with detailed steps required to complete a task. If you require more info, each section has links to the relevant documentation.

Many of the topics in this article assume that you are using the Unity dependency injection container, and that you are using conventions defined by Prism. This guidance is provided to make it easier for you to understand how to get started with Prism. However, you are not required to use Unity, or any other dependency injection container, and you do not have to use the default conventions to associate views and view models. To understand how to use Prism without a dependency injection container, or change the default conventions, see Changing the convention for naming and locating views, Changing the convention for naming, locating, and associating view models with views, Registering a view model factory with views instead of using a dependency injection container.

For more info about the conventions defined by Prism, see Using a convention-based approach to connect view models to views. For more info about Prism, see Prism for the Windows Runtime reference.

Architecture of a Windows Store business app that uses Prism

Developers of Windows Store business apps face several challenges. App requirements can change over time. New business opportunities and challenges may present themselves. Ongoing customer feedback during development may significantly affect the requirements of the app. Therefore it's important to build an app that it is flexible and can be easily modified or extended over time.

Prism for the Windows Runtime provides an architecture that helps to do just that. It is designed to help developers create apps that need to accomplish the following:

  • Address the common Windows Store app development scenarios.
  • Separate the concerns of presentation, presentation logic, and model through support for Model-View-ViewModel (MVVM).
  • Use an architectural infrastructure to produce a consistent and high quality app.

The logical architecture of a typical Windows Store business app that uses Prism is shown in the following diagram.

This architecture is used by the AdventureWorks Shopper reference implementation. However, there are also alternative architectures that are equally valid.

The architecture provided by Prism helps to produce flexible, maintainable, and testable apps. It includes components that help to accelerate development of your app by providing support for MVVM, loosely coupled communication, and the core services required in Windows Store apps, allowing you to focus on developing the user experiences for your app. For more info see Prism for the Windows Runtime reference.

[Top]

Creating a Windows Store app project using Prism and Unity

The following procedure shows how to update a Windows Store app to use the services provided by Prism.

  1. Add a reference to the Microsoft.Practices.Prism.StoreApps library to your project to use the services provided by the library.

  2. Derive the App class from the MvvmAppBase class, provided by the Microsoft.Practices.Prism.StoreApps library, in order to gain support for MVVM and the core services required by Windows Store apps.

  3. Delete the OnLaunched and OnSuspending methods from the App class, as these methods are provided by the MvvmAppBase class.

  4. Override the OnLaunchApplication abstract method of the MvvmAppBase class, in the App class, and add code to navigate to the first page of the app.

    protected override Task OnLaunchApplication(LaunchActivatedEventArgs args)
    {
       NavigationService.Navigate("PageName", null);
       return Task.FromResult<object>(null);
    }
    

    The OnLaunchApplication method returns a Task, allowing it to launch a long running operation. If you don't have a long running operation to launch you should return an empty Task.

    Note  PageName should be without the "Page" suffix. For example, use Home for HomePage.

     

  5. Add a reference to the Unity library to your project to use the Unity dependency injection container.

    Note  The Microsoft.Practices.Prism.StoreApps library is not dependent on the Unity library. To avoid using a dependency injection container see Registering a view model factory with views instead of using a dependency injection container.

     

  6. Create an instance of the UnityContainer class in the App class, so that you can use the Unity dependency injection container to register and resolve types and instances.

    private readonly IUnityContainer _container = new UnityContainer();
    
  7. Override the OnRegisterKnownTypesForSerialization method in the App class to register any non-primitive types that need to be saved and restored to survive app termination.

    SessionStateService.RegisterKnownType(typeof(Address));
    
  8. Override the OnInitialize method in the App class in order to register types for the Unity container and perform any other initialization. Examples of app specific initialization behavior include:

    • Registering infrastructure services.
    • Registering types and instances that you use in constructors.
    • Providing a delegate that returns a view model type for a given view type.
    protected override void OnInitialize(IActivatedEventArgs args)
    {
        _container.RegisterInstance(NavigationService);
        _container.RegisterType<IAccountService, AccountService>(new ContainerControlledLifetimeManager());
        _container.RegisterType<IShippingAddressUserControlViewModel, ShippingAddressUserControlViewModel>();
    
        ViewModelLocator.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
            {
                ...
                return viewModelType;
            }); 
    }
    

    Note  For a detailed example of an OnInitialize method see the App class in the AdventureWorks Shopper reference implementation.

     

  9. Override the Resolve method in the App class to return a constructed view model instance.

    protected override object Resolve(Type type)
    {
        return _container.Resolve(type);
    }
    

For more info see Using the MVVM pattern, Registering a view model factory with views instead of using a dependency injection container, Bootstrapping an MVVM Windows Store app Quickstart, Creating and navigating between pages and Prism for the Windows Runtime reference.

[Top]

Creating a view

The following procedure shows how to create a view class that has support for layout changes, navigation, and state management.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Add a folder named Views to the root folder of your project.

  3. Create a new page in the Views folder whose name ends with "Page," in order to use the FrameNavigationService's default convention to navigate to pages in the Views folder.

  4. Modify the page class to derive from the VisualStateAwarePage class, which provides support for layout changes, navigation, and state management.

  5. Add the ViewModelLocator.AutoWireViewModel attached property to your view XAML in order to use the ViewModelLocator class to instantiate the view model class and associate it with the view class.

    prism:ViewModelLocator.AutoWireViewModel="true"
    
  6. Override the OnNavigatedTo and OnNavigatedFrom methods if your page class needs to perform additional logic, such as subscribing to an event or unsubscribing from an event, when page navigation occurs. Ensure that the OnNavigatedTo and OnNavigatedFrom overrides call base.OnNavigatedTo and base.OnNavigatedFrom, respectively.

  7. Override the SaveState and LoadState methods if you have view state, such as scroll position, that needs to survive termination and be restored when the app is reactivated.

For more info see Creating and navigating between pages, Using the MVVM pattern, and Handling suspend, resume, and activation.

[Top]

Creating a view model class

The following procedure shows how to create a view model class that has support for property change notification, navigation, and state management.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.
  2. Add a folder named ViewModels to the root folder of your project.
  3. Create a new class in the ViewModels folder whose name corresponds with the name of a view and ends with "ViewModel," in order to use the ViewModelLocator's default convention to instantiate and associate view model classes with view classes.
  4. Derive the view model class from the ViewModel base class, provided by the Microsoft.Practices.Prism.StoreApps library, so that you can use the base class's implementation of the INotifyPropertyChanged interface and gain support for navigation and state management.
  5. Modify the view model constructor so that it accepts the services required by the view model, such as an INavigationService instance.
  6. Annotate properties with the [RestorableState] custom attribute if you want their values to survive termination.

For more info see Using the MVVM pattern.

[Top]

Creating a model class with validation support

The following procedure shows how to create a model class that has support for validation.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Add a reference to the Behaviors SDK (XAML) library to your project to use Blend for Microsoft Visual Studio 2013 behaviors.

  3. Add a model class to your project and derive the model class from the ValidatableBindableBase class, which provides validation support.

  4. Add a property to the model class and add the appropriate attributes that derive from the ValidationAttribute attribute, in order to specify the client side validation.

    [Required(ErrorMessage = "First name is required.")]
    public string FirstName
    {
        get { return _firstName; }
        set { SetProperty(ref _firstName, value); }
    }
    
  5. Update the view XAML that binds to the property created in the previous step to show validation error messages.

    <TextBox Text="{Binding UserInfo.FirstName, Mode=TwoWay}">
        <interactivity:Interaction.Behaviors>
            <awbehaviors:HighlightFormFieldOnErrors PropertyErrors="{Binding UserInfo.Errors[FirstName]}" />
        </interactivity:Interaction.Behaviors>
    </TextBox>
    

    Note  The HighlightFormFieldOnErrors behavior can be found in the AdventureWorks Shopper reference implementation.

     

For more info Validating user input and Validation Quickstart.

[Top]

Adding items to the Settings pane

The following procedure shows how to add an item to the Settings pane that can invoke an action.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Override the GetSettingsCommands method in the App class and add code to add items to the Settings pane.

    protected override IList<SettingsCommand> GetSettingsCommand()
    {
        var settingsCommands = new List<SettingsCommand>();
        settingsCommands.Add(new SettingsCommand(Guid.NewGuid().ToString(), "Text to show in Settings pane", ActionToBePerformed));
        settingsCommands.Add(new SettingsCommand(Guid.NewGuid().ToString(), "Custom setting", () => new CustomSettingFlyout().Show()));
        return settingsCommands;
    }
    

For more info see Managing application data.

[Top]

Changing the Prism conventions

This section describes how to change the conventions for naming and locating views, naming, locating and associating view models with views, and registering a view model factory with views instead of using a dependency injection container.

Changing the convention for naming and locating views

The following procedure shows how to configure the FrameNavigationService class to look for views in a location other than the Views folder.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Override the GetPageType method in the App class and add code to define the page location and naming convention appropriate to your app.

    protected override Type GetPageType(string pageToken)
    {
        var assemblyQualifiedAppType = this.GetType().GetTypeInfo().AssemblyQualifiedName;
        var pageNameWithParameter = assemblyQualifiedAppType.Replace(this.GetType().FullName, this.GetType().Namespace + ".Pages.{0}View");
        var viewFullName = string.Format(CultureInfo.InvariantCulture, pageNameWithParameter, pageToken);
        var viewType = Type.GetType(viewFullName);
        return viewType;
    }
    

For more info see Using the MVVM pattern.

[Top]

Changing the convention for naming, locating, and associating view models with views

The following procedure shows how to configure the ViewModelLocator class to look for view models in a location other than the ViewModels folder in the same assembly.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Override the OnInitialize method in the App class and invoke the static ViewModelLocator.SetDefaultViewTypeToViewModelTypeResolver method, passing in a delegate that specifies a view type and returns a corresponding view model type.

    protected override void OnInitialize(IActivatedEventArgs args)
    {
        ...
        ViewModelLocator.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
            {
                var viewModelTypeName = string.Format(CultureInfo.InvariantCulture, "MyProject.VMs.{0}ViewModel, MyProject, Version=1.0.0.0, Culture=neutral, 
                                                      PublicKeyToken=public_Key_Token", viewType.Name);
                var viewModelType = Type.GetType(viewModelTypeName);
                return viewModelType;
            });
        ...
    }
    

For more info see Using the MVVM pattern.

[Top]

Registering a view model factory with views instead of using a dependency injection container

The following procedure shows how to configure the ViewModelLocator class to explicitly specify how to construct a view model for a given view type, instead of using a container for dependency resolution and construction.

  1. Complete the Creating a Windows Store app project using Prism and Unity procedure.

  2. Override the OnInitialize method in the App class and register a factory with the ViewModelLocator class that will create a view model instance that will be associated with a view.

    protected override void OnInitialize(IActivatedEventArgs args)
    {
        ...
        ViewModelLocator.Register(typeof(MyPage).ToString(), () => new MyPageViewModel(NavigationService));
        ...
    }
    

For more info see Using the MVVM pattern and Bootstrapping an MVVM Windows Store app Quickstart.

[Top]