Prism Framework

repository·master·Indexed 41 days ago

https://github.com/prismlibrary/prism-documentation

A framework for building loosely coupled, maintainable, and testable XAML applications across WPF, Windows 10 UWP, and Xamarin Forms. Version 9.1.0 includes features such as IAsyncCommand for asynchronous operations, DelegateCommand for ViewModel action encapsulation, and CompositeCommand for managing groups of child commands.

Tokens
71.3K
Snippets
209
Records
280
Agent score
39%

What's inside Prism

  1. Introduction to Prism

    master

    Prism is a framework designed for building loosely coupled, maintainable, and testable XAML applications. It is compatible with several platforms, including WPF, .NET MAUI, Uno Platform, and Avalonia. Each platform has separate releases developed on independent timelines.

    Prism implements several key design patterns to help structure XAML applications:

    • MVVM (Model-View-ViewModel)
    • Dependency Injection
    • Commands
    • EventAggregator

    The core functionality is shared via a Cross Compiled .NET Standard and .NET 4.5/4.8 Library, while platform-specific implementations are handled in their respective libraries. Prism 9 specifically focuses on unifying the API across all platforms to maximize code reuse and ease of migration between platforms.

  2. Overview of Prism Framework

    master

    Prism is a framework designed to help developers build loosely coupled, maintainable, and testable XAML-based applications. It is specifically built for the following platforms:

    • WPF (Windows Presentation Foundation)
    • Windows 10 UWP (Universal Windows Platform)
    • Xamarin.Forms
  3. Explore Prism navigation topics

    master

    Prism provides several specialized capabilities for managing navigation in MVVM applications. Depending on your requirements, you may need to implement one of the following:

    • Basic Region Navigation: The foundational system for navigating within regions.
    • Confirming Navigation: Implementing logic to allow or intercept user navigation (e.g., preventing navigation if a form is unsaved).
    • Controlling View Lifetime: Configuring views to remain in memory even after the user has navigated away from them.
    • Navigate Existing Views: Navigating between views that are already active.
    • Navigation Journal: Using a journal to allow users to navigate through their history from within the view.
    • Passing Parameters: Sending data to the view being navigated to.
    • View and View Model Participation: Linking your views and view models to the Prism navigation system.
    • Global Region Observer: Observing and reacting to Navigation Events globally.
  4. Navigate to WPF-specific Prism documentation

    master

    This section serves as a hub for WPF-specific implementations of Prism features. For general Prism concepts that are not WPF-specific, refer to the core documentation. Key topics covered in the WPF section include:

    • Commanding: Binding actions (like button clicks) to ViewModels.
    • Composite Commands: Executing commands in child ViewModels from a parent ViewModel.
    • View Model Injection: Using naming conventions to automatically inject ViewModels.
    • Event Aggregation: Decoupled communication between components.
    • Application Modularity: Structuring applications into decoupled, maintainable pieces.
    • Dialog Services: Presenting child windows in an MVVM-friendly way.
  5. What is the ContainerLocator and when to use it

    master

    The ContainerLocator is a mechanism introduced in Prism 8.0 to manage the container instance, replacing the older CommonServiceLocator dependency. It is particularly useful in scenarios where Prism needs to fall back to a Service Locator pattern (such as within XAML Extensions) or in cross-platform applications (like .NET MAUI or Uno Platform) where you need to initialize the container before the Prism application starts.

    A common use case is integrating with libraries like Shiny, where you can add a ServiceCollection to your Prism container and return the IServiceProvider to Shiny, ensuring both libraries share a single container instance.

  6. What is navigation in Prism?

    master

    In Prism, navigation is the process of coordinating UI changes resulting from user interaction or internal application state changes. Prism supports two primary types of navigation:

    1. State Based Navigation: Accomplished via state changes to existing controls within the visual tree (e.g., hiding/showing controls or updating data within a control).
    2. View Based Navigation: Accomplished via the addition or removal of elements from the visual tree (e.g., swapping one view for another).

    Prism is designed to facilitate these patterns in composite MVVM applications where the UI (View) is separated from the presentation logic (ViewModel).

  7. Share data between regions using RegionContext

    master

    The RegionContext attached property allows you to share context (data) between a parent view and all child views hosted within a specific region. This is distinct from WPF's DataContext, which is local to a single view.

    Setting RegionContext

    In XAML:

    <TabControl 
        prism:RegionManager.RegionName="{x:Static local:RegionNames.TabRegion}"
        prism:RegionManager.RegionContext="{Binding Path=SelectedEmployee.EmployeeId}" />

    In Code:

    RegionManager.Regions["Region1"].Context = employeeId;

    Retrieving RegionContext

    In a view, use the static RegionContext.GetObservableContext(this) method. This returns an ObservableObject<object> which you can use to access the Value property.

    To react to changes in the context, subscribe to the PropertyChanged event on the returned ObservableObject.

    Note: The content object hosting the region must derive from DependencyObject (e.g., a WPF control or a ViewModel that inherits from DependencyObject) to support the attached property.

    // Retrieving context in a view
    private void GetRegionContext()
    {
        this.Model.EmployeeId = (int)RegionContext.GetObservableContext(this).Value;
    }
    
    // Subscribing to changes
    ObservableObject<object> viewRegionContext = RegionContext.GetObservableContext(this);
    viewRegionContext.PropertyChanged += this.ViewRegionContext_OnPropertyChangedEvent;
    
    private void ViewRegionContext_OnPropertyChangedEvent(object sender, PropertyChangedEventArgs args)
    {
        if (args.PropertyName == "Value")
        {
            var context = (ObservableObject<object>)sender;
            int newValue = (int)context.Value;
        }
    }
  8. Use IServiceCollection extensions with Prism 9.0

    master

    Prism 9.0 includes a core reference to Microsoft.Extensions.DependencyInjection.Abstractions. This allows you to leverage registration extensions from third-party packages that were designed for Microsoft.Extensions.DependencyInjection (such as Entity Framework Core or HttpClientFactory) directly within your Prism container implementations.

    While Prism continues to use IContainerRegistry and IContainerProvider (following the pattern established in Prism 7.0), the inclusion of these abstractions ensures that container implementations can support standard .NET dependency injection extensions natively.

  9. Choose an available Store type

    master

    Prism provides three default store implementations. Choose the one that matches your data's lifecycle and security requirements:

    • Memory Store: Values remain in scope only during the application lifecycle. Data is lost when the app is closed.
    • Settings Store: Used for persistent values that do not require high security (e.g., user preferences).
    • Secure Store: Used for persistent values that require platform-level security (e.g., sensitive tokens).
      • Note: Some platforms, such as WASM, do not support the Secure Store.
  10. How the ViewModelLocator works

    master

    The ViewModelLocator automatically wires a View's DataContext to an instance of a ViewModel. It uses an attached property called AutoWireViewModel to trigger this process.

    Default Behavior

    • WPF: Auto-wiring is enabled by default only when using region navigation and IDialogService. If using view injection, you must explicitly opt-in.
    • .NET MAUI: Auto-wiring is enabled by default and is opt-out only. It is required to provide the correct INavigationService instance to the ViewModel.

    Resolution Logic

    When resolving a ViewModel, the ViewModelLocationProvider follows this priority:

    1. Explicit Mappings: Checks any mappings registered via ViewModelLocationProvider.Register.
    2. Convention-based Fallback: If no mapping exists, it uses a naming convention. The default convention assumes:
      • ViewModels and Views are in the same assembly.
      • ViewModels are in a .ViewModels child namespace.
      • Views are in a .Views child namespace.
      • ViewModel names match the View names but end with ViewModel (e.g., MainWindow -> MainWindowViewModel).
    <!-- Opt-out of auto-wiring in XAML -->
    <Window x:Class="Demo.Views.MainWindow"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="False">
  11. Absolute vs Relative Navigation URIs

    master

    Prism distinguishes between Absolute and Relative URIs to determine how the navigation stack is modified:

    • Absolute URIs: Start with a / (e.g., /ViewA). These set a new Page on the Application Window.
    • Relative URIs: Do not start with /. These push a new Page onto the current Navigation Stack.

    Relative Navigation Shortcuts: You can use ../ to navigate back one level. You can also combine this to navigate back and forward simultaneously. For example, if your stack is NavigationPage/ViewA/ViewB and you are in ViewB, navigating to ../ViewC will pop ViewB and push ViewC onto the stack.

  12. Integrate Raygun with Prism.Essentials

    master

    The Raygun implementation of the Logger integrates with the Prism.Plugin.Essentials library to provide enhanced features:

    • Offline Support: If Essentials interfaces are registered, the logger automatically enables offline support with request caching.
    • Application Context: The logger automatically uses the Application Context from Essentials for configuration.
    • Background Sending: To enable sending logs in the background using the offline store, you must register Prism.Plugin.Essentials before configuring Raygun logging.

    Requirement: Ensure Prism.Plugin.Essentials is registered first in your container configuration to benefit from these features.