Microsoft UI XAML

repository·main·Indexed 27 days ago

https://github.com/microsoft/microsoft-ui-xaml

UI components and infrastructure for building Windows applications. Includes documentation for controls such as ColorPicker (and its associated ColorPickerSlider, ColorSpectrum, and SpectrumBrush), NavigationView, and PagerControl, covering architecture, template parts, and API usage.

Tokens
194.5K
Snippets
385
Records
1K
Agent score
92%

What's inside microsoft-ui-xaml

  1. Overview of Xaml Islands

    main

    A Xaml Island allows you to host chunks of Xaml content within a different UI framework (such as Win32, WPF, or WinForms).

    Depending on your environment and SDK version, you will use one of two primary APIs:

    1. XamlIsland: The modern API introduced in WinAppSDK 1.7 (March 2025). This is the intended replacement for DesktopWindowXamlSource in WinUI3.
    2. DesktopWindowXamlSource: The legacy API available in System Xaml (2019) and WinAppSDK 1.4.
  2. Overview of Read-Only Text Controls

    main

    XAML provides several non-editable (read-only) text controls for displaying content. Unlike editable controls (like TextBox), these are derived from FrameworkElement rather than Control, meaning they are not templated and cannot receive keyboard focus.

    Key controls include:

    • TextBlock: Supports a single collection of inline elements that flow together as one "block" (paragraph).
    • RichTextBlock: Supports multiple blocks (paragraphs), where each block contains its own collection of inline elements.
    • RichTextBlockOverflow: Used when content exceeds the bounds of a RichTextBlock. It can be chained together, and formatting continues seamlessly from the source RichTextBlock.
    • Glyphs: A primitive control that displays a single glyph run. It does not use LineServices for layout and lacks advanced text layout capabilities.
  3. Overview of XAML Rendering Architecture Components

    main

    The XAML rendering engine is structured in layers:

    1. App Layer: The top layer where application code is built using XAML APIs.
    2. XAML Layer: The core framework providing the element tree and management logic.
    3. Compositor Layer (WUC/DComp): XAML uses either Windows.UI.Composition (WUC) or DirectComposition (DComp) to describe the rendering scene-graph via a Visual tree. This tree is sent to the Desktop Window Manager (DWM).
    4. Graphics Layer (D2D/D3D): XAML manages its own graphics resources (like video memory bitmaps for images, text, and shapes) directly using Direct2D and Direct3D, sharing these resources with the system compositor.
  4. Overview of ColorPicker Architecture

    main

    The ColorPicker control suite consists of several specialized components designed for color selection. The primary control for application developers is ColorPicker.

    Core Components:

    • ColorPicker (Microsoft.UI.Xaml.Controls): The top-level control for user interaction.
    • ColorPickerSlider (Microsoft.UI.Xaml.Controls.Primitives): A specialized 1D slider used within the ColorPicker template to represent HSV channels or Alpha. It features a gradient background corresponding to the color channel.
    • ColorSpectrum (Microsoft.UI.Xaml.Controls.Primitives): A 2D graphic (Box or Ring shape) for selecting colors.
    • SpectrumBrush (Microsoft.UI.Xaml.Controls.Primitives): A composition-based brush for rendering the spectrum background (requires Windows 1703/RS2 or later).

    Helper Utilities:

    • ColorHelpers: Specific to the ColorPicker controls.
    • ColorConversion: Provides generalized RGB/HSV/Hex conversions and structures.
  5. Overview of ItemsRepeater and related components

    main

    The ItemsRepeater is a WinUI building block used for creating controls that display item collections. It is designed to be highly flexible and serves as the foundation for several high-level controls.

    Core Components

    • ItemsSourceView: Works alongside ItemsRepeater.
    • Built-in Layouts: StackLayout, UniformGridLayout, and LinedFlowLayout.
    • Animations: ItemCollectionTransitionProvider (with LinedFlowLayoutItemCollectionTransitionProvider as a built-in option).

    Preview Features

    Note that the following features are currently in preview and may undergo changes:

    • ElementFactory
    • RecyclePool / RecyclingElementFactory
    • FlowLayout
    • SelectionModel / IndexPath for selection management.
  6. Overview of ScrollView responsibilities

    main

    The ScrollView control provides high-level scrolling and zooming capabilities by wrapping an inner ScrollPresenter. Its primary responsibilities include:

    • Default Chrome: Provides conscious scrollbars, scroll indicators, and a scroll indicator separator. It manages IScrollController implementations (such as the ScrollBar control) for both horizontal and vertical dimensions.
    • Input Support: Provides default support for UI-thread bound keyboard and gamepad inputs.
    • Focus Management: Handles default focus movement for gamepads and ensures proper focus rectangle clipping.
    • Accessibility: Provides default accessibility support and respects user system settings (e.g., disabling conscious scrollbars).
    • Snap Points: Simplifies the configuration of snap points by consuming IScrollSnapPointsInfo implementations and forwarding them to the inner ScrollPresenter.
  7. Understand the XAML Compiler Architecture

    main

    The XAML Compiler consists of several layers designed to transform XAML markup into compiled code and binary XBF files.

    Core Components

    • CompileXaml / xamlcompiler.exe: The outermost layer. CompileXaml is an MSBuild Task, while xamlcompiler.exe is a standalone executable. Both pass parameters to the shared inner layer.
    • CompileXamlInternal: The shared inner layer and main entrypoint via CompileXamlInternal.DoExecute. It handles argument validation, type resolution (via Type Universe, Schema Context, and Type Resolver), XAML validation, code-behind generation, XAML rewriting, XBF generation (via genxbf.dll), and binding info generation.
    • Type Resolution: Uses the Light Metadata Reader (LMR) to extract types from assemblies (dll and winmd). These objects are cached to optimize subsequent invocations.
    • Xaml Dom Validation: The XamlDomValidator performs early checks on namespaces, elements, members, directives, and x:Bind usage. It acts as a first line of defense but is limited because it cannot inspect local types.
    • Xaml Rewriting: The XamlConnectionIdRewriter modifies XAML before it reaches genxbf. It removes members like x:Name, Events, x:Bind, and x:DataType, and adds members like x:ConnectionId and x:Load="false" to preserve line/column information for debugging.
  8. Use ScrollPresenter for custom scrolling and zooming

    main

    The ScrollPresenter is a FrameworkElement used as a container to allow users to pan, zoom, and scroll content. It is a low-level primitive that provides the core scrolling logic without the visual chrome (like scrollbars) or keyboard handling found in ScrollView.

    Key concepts:

    • Extent: The total area occupied by all content.
    • Viewport: The visible area of the content.

    Use ScrollPresenter when you need to build a custom scrolling control or when you want to manage scrolling/zooming behavior without the default UI widgets provided by ScrollView.

  9. Compare System XAML vs WinUI 3 XAML Islands DispatcherQueue handling

    main

    In System XAML, the application is responsible for manually running a message pump and draining the DispatcherQueue during shutdown to process asynchronous tasks scheduled during the WindowsXamlManager cleanup.

    System XAML Shutdown Pattern:

    1. Initialize Windows::UI::Xaml::WindowsXamlManager.
    2. Run a standard GetMessage loop.
    3. Call .Close() on the WindowsXamlManager instance.
    4. Manually drain the DispatcherQueue using a PeekMessage loop to ensure all async work is processed.
    5. Shut down the DispatcherQueueController if one was created.

    WinUI 3 aims to improve this by requiring the app to provide the DispatcherQueue on the thread, avoiding the issues where XAML creates a DispatcherQueueController that it cannot correctly shut down.

    // System XAML Shutdown Example
    
    auto wxm = Windows::UI::Xaml::WindowsXamlManager::InitializeForCurrentThread();
    
    // Run the message pump
    MSG msg; 
    while (GetMessage(&msg, nullptr, 0, 0)) 
    {
        if (!CallPreTranslateMessageHelper()) 
        {
            TranslateMesasge(&msg); 
            DispatchMessage(&msg); 
        }
    }
    
    // Cleanup
    wxm.Close();
    
    // Drain the DispatcherQueue to process async work
    while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { DispatchMessage(&msg); }
    
    ShutdownDispatcherQueueController();
  10. Understand the CompNode and Visual tree architecture

    main

    XAML rendering uses two distinct tree structures to build the final visual output:

    1. CompNode Tree: An intermediate tree used to encapsulate the logic for setting up the Visual tree and mapping properties. A CUIElement generates a CompNode tree when it requires independent animations or specific composition features (see CUIElement::RequiresComposition() for details).
    2. Visual Tree: The final tree of composition visuals used by the compositor to render the UI.

    CompNode Types

    • Tree Node (HWCompTreeNode and derived): Acts as the "spine" of the tree. It maps CUIElement properties to Visual properties using multiple Visuals. It can have child CompNodes.
    • Content Node (HWCompLeafNode, HWCompRenderDataNode): Carries the Visuals that actually draw the content of a CUIElement and its subtree. Content nodes cannot have child CompNodes.

    Standard CompNode Generation

    When a CUIElement requires a CompNode, XAML typically generates three nodes:

    1. TreeNode: Carries properties and serves as the parent for the ContentNode and child TreeNodes.
    2. ContentNode: The first child of the TreeNode; carries the content of the element and its subtree.
    3. Post-Subgraph Node: The next sibling of the TreeNode; carries content of the "right" subtree that draws higher in z-order.
  11. Understand the ItemsView and ItemContainer controls

    main

    The ItemsView is a modern control designed for representing item collections, serving as a replacement for the older ListView and GridView. It is built using ItemsRepeater, SelectionModel, and ScrollView.

    Key characteristics:

    • ItemsView: Supports pluggable layouts (e.g., StackLayout, UniformGridLayout, LinedFlowLayout), custom animators via ItemTransitionProvider, and custom vertical scroll controllers via VerticalScrollController. It supports index-based and location-based keyboard navigation.
    • ItemContainer: A lightweight control that hosts each individual item within the ItemsView.

    Important Constraint: Any custom ItemTemplate used with ItemsView must currently use an ItemContainer at its root.