### XML Documentation for Button Control with Multiple XAML Examples Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Demonstrates XML documentation for a Button control, including multiple XAML usage examples within the tag. ```csharp /// /// Inherited from the , /// adding . /// /// /// /// <ui:Button /// Appearance="Primary" /// Content="WPF UI button with font icon" /// Icon="{ui:SymbolIcon Symbol=Fluent24}" /> /// /// /// <ui:Button /// Appearance="Primary" /// Content="WPF UI button with font icon" /// Icon="{ui:FontIcon '🌈'}" /> /// /// ``` -------------------------------- ### Unit Test Template Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Provides example file paths for unit test templates. ```text tests/Wpf.Ui.UnitTests/Animations/TransitionAnimationProviderTests.cs tests/Wpf.Ui.UnitTests/Extensions/SymbolExtensionsTests.cs ``` -------------------------------- ### Install WPF UI via Winget Source: https://github.com/lepoco/wpfui/blob/main/README.md Use Winget to install the WPF UI package. This is a quick way to get started with the library. ```powershell winget install 'WPF UI' ``` -------------------------------- ### Instance-Based Manager with DI Setup Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Illustrates the setup required for an instance-based theme manager using dependency injection, including registration in `App.xaml.cs` and constructor injection in a window. ```csharp // App.xaml.cs services.AddSingleton(); // MainWindow.xaml.cs public MainWindow(IThemeManager themeManager) { _themeManager = themeManager; InitializeComponent(); _themeManager.Apply(ApplicationTheme.Dark); } ``` -------------------------------- ### Instance-Based Manager Usage Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Contrasts the direct API usage with an example of how a theme manager would be used if it were an instance-based service, requiring context about its origin. ```csharp // Requires context about where themeManager comes from _themeManager.Apply(ApplicationTheme.Dark); var current = _themeManager.GetAppTheme(); ``` -------------------------------- ### Install WPF UI Gallery via Winget Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/gallery.md Use the Windows Package Manager to install the WPF UI Gallery application. ```powershell $ winget install 'WPF UI' ``` -------------------------------- ### Integration Test Template Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Provides example file paths for integration test templates. ```text tests/Wpf.Ui.Gallery.IntegrationTests/TitleBarTests.cs tests/Wpf.Ui.Gallery.IntegrationTests/NavigationTests.cs ``` -------------------------------- ### XML Documentation for C# Code Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Provides an example of XML documentation for C# code, specifically for static managers, using the tag with a block. ```csharp /// /// /// ApplicationThemeManager.Apply( /// ApplicationTheme.Light /// ); /// /// ``` -------------------------------- ### Example Event Argument File Names Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Illustrative examples of event argument file names, demonstrating the application of the naming convention for specific controls and events. ```text - `ContentDialogButtonClickEventArgs.cs` ``` ```text - `NavigatedEventArgs.cs` ``` -------------------------------- ### Control Folder README Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md An example of a README.md file within a complex control's folder. This file serves to document the control's specific usage, structure, and any unique considerations. ```markdown Each complex control folder includes README.md: ``` -------------------------------- ### Implement WPF UI Controls Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/getting-started.md Example of using the ui prefix to instantiate a library control, such as SymbolIcon, within the MainWindow. ```xml ``` -------------------------------- ### Unit Test Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Demonstrates unit testing conventions using xUnit.Fact for testing the ApplyTransition method. ```csharp public class TransitionAnimationProviderTests { [Fact] public void ApplyTransition_ReturnsFalse_WhenDurationIsLessThan10() { UIElement mockedUiElement = Substitute.For(); var result = TransitionAnimationProvider.ApplyTransition(mockedUiElement, Transition.FadeIn, -10); Assert.False(result); } [Fact] public void ApplyTransition_ReturnsFalse_WhenElementIsNull() { var result = TransitionAnimationProvider.ApplyTransition(null, Transition.FadeIn, 1000); Assert.False(result); } } ``` -------------------------------- ### Unit Test Example for MyControl Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Provides unit tests for the MyControl component, covering constructor, property changes, and icon handling. Ensure NSubstitute and Xunit are installed. ```csharp // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using System.Windows; using NSubstitute; using Wpf.Ui.Controls; using Xunit; namespace Wpf.Ui.UnitTests.Controls; public class MyControlTests { [Fact] public void Constructor_ShouldSetDefaultValues() { // Arrange & Act var control = new MyControl(); // Assert Assert.Equal(ControlAppearance.Primary, control.Appearance); Assert.Null(control.Icon); Assert.False(control.IsCustom); } [Fact] public void Appearance_ShouldUpdateWhenSet() { // Arrange var control = new MyControl(); // Act control.Appearance = ControlAppearance.Secondary; // Assert Assert.Equal(ControlAppearance.Secondary, control.Appearance); } [Fact] public void IsCustomChanged_ShouldInvokeCallback_WhenValueChanges() { // Arrange var control = new MyControl(); bool callbackInvoked = false; // Subscribe to property change if there's a routed event // Or test via reflection if the method is protected // Act control.IsCustom = true; // Assert Assert.True(control.IsCustom); } [Fact] public void Icon_ShouldAcceptSymbolIcon() { // Arrange var control = new MyControl(); var icon = new SymbolIcon { Symbol = SymbolRegular.Heart24 }; // Act control.Icon = icon; // Assert Assert.Equal(icon, control.Icon); } } ``` -------------------------------- ### Immediate Usability Without DI Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Demonstrates applying a theme directly in a WPF window's constructor without any prior dependency injection setup, showcasing the immediate usability of static managers. ```csharp // Works immediately without setup public MainWindow() { InitializeComponent(); ApplicationThemeManager.Apply(ApplicationTheme.Dark); } ``` -------------------------------- ### XML Documentation for Anchor Control Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Public APIs require and tags. This example shows XAML usage for the Anchor control. ```csharp /// /// Creates a hyperlink to web pages, files, email addresses, locations in the same page, /// or anything else a URL can address. /// /// /// /// <ui:Anchor /// NavigateUri="https://lepo.co/" /> /// /// public class Anchor : Wpf.Ui.Controls.HyperlinkButton { } ``` -------------------------------- ### Integration Test Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Shows integration testing practices using UiTest base class, FlaUI, and AwesomeAssertions for UI interactions. ```csharp public sealed class TitleBarTests : UiTest { [Fact] public async Task CloseButton_ShouldCloseWindow_WhenClicked() { Button? closeButton = FindFirst("TitleBarCloseButton").AsButton(); closeButton.Should().NotBeNull("because CloseButton should be present in the main window title bar"); closeButton.Click(moveMouse: false); await Wait(2); Application ?.HasExited.Should() .BeTrue("because the main window should be closed after clicking the close button"); } } ``` -------------------------------- ### Commit Convention Examples Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Illustrates the commit message format 'type(scope): description (#PR_NUMBER)' with various examples. ```git fix(controls): Fix TextBlock issues (#1640) fix(controls): Remove AnimationFactorToValueConverter from CheckBox.xaml (#1649) fix(controls): NavigationViewItemAutomationPeer followup (#1646) fix(controls): Update ContentDialog For TitleBar CenterContent (#1642) feat(app): Add ability to disable automatic apply of system accent color in UiApplication (#1643) ``` -------------------------------- ### Incorrect Directory Level Nesting Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Shows an example of excessive directory nesting under Controls/, which is not allowed. The structure should not exceed two directory levels. ```text ✅ Controls/ContentDialog/EventArgs/ ``` ```text ❌ Controls/ContentDialog/EventArgs/Closing/ ``` -------------------------------- ### ViewModel Setup for Navigation Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md Define collections for navigation items and bind them to the NavigationView in your MainWindowViewModel. Ensure properties are observable. ```csharp public partial class MainWindowViewModel : ObservableObject { [ObservableProperty] private ICollection _menuItems = new ObservableCollection(); [ObservableProperty] private ICollection _footerMenuItems = new ObservableCollection(); public MainWindowViewModel() { MenuItems = new ObservableCollection { new NavigationViewItem("Home", SymbolRegular.Home24, typeof(DashboardPage)), new NavigationViewItem("Data", SymbolRegular.DataHistogram24, typeof(DataPage)) }; FooterMenuItems = new ObservableCollection { new NavigationViewItem("Settings", SymbolRegular.Settings24, typeof(SettingsPage)) }; } } ``` -------------------------------- ### Feature Folder Structure Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Illustrates the directory structure for organizing controls, with each control residing in its own folder containing related files. ```tree Controls/ ├── Button/ │ ├── Button.cs │ └── Button.xaml ├── Card/ │ ├── Card.cs │ └── Card.xaml ├── NavigationView/ │ ├── NavigationView.Base.cs │ ├── NavigationView.Properties.cs │ ├── NavigationView.Events.cs │ ├── NavigationView.Navigation.cs │ ├── NavigationView.TemplateParts.cs │ ├── NavigationView.AttachedProperties.cs │ ├── NavigationView.xaml │ ├── NavigationViewItem.cs │ ├── NavigationViewItemHeader.cs │ └── NavigationViewItemSeparator.cs ``` -------------------------------- ### Create a Basic Fluent Window with a Button Source: https://github.com/lepoco/wpfui/blob/main/README.md Example of creating a simple WPF UI application window with a TitleBar and a Button. This demonstrates the basic structure and usage of WPF UI controls within a FluentWindow. ```xml ``` -------------------------------- ### Direct API Usage Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Shows the simple and direct way to interact with the static `ApplicationThemeManager` for applying a theme and retrieving the current theme, highlighting the clarity of the global scope. ```csharp // Immediate clarity of global scope ApplicationThemeManager.Apply(ApplicationTheme.Dark); var current = ApplicationThemeManager.GetAppTheme(); ``` -------------------------------- ### Integration Test Example for MyControl Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Demonstrates integration tests for MyControl's visibility, appearance changes, enabled state, and command execution. Requires AwesomeAssertions and FlaUI. ```csharp // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using AwesomeAssertions.Autofac; using FlaUI.Core.AutomationElements; using Wpf.Ui.Gallery.IntegrationTests.Fixtures; using Xunit; namespace Wpf.Ui.Gallery.IntegrationTests; public sealed class MyControlTests : UiTest { [Fact] public async Task MyControl_ShouldBeVisible_WhenPageLoads() { // Arrange await NavigateToPage("MyControl"); // Act var control = Window.FindFirstDescendant(cf => cf.ByAutomationId("MyControlExample")); // Assert control.Should().NotBeNull(); control.IsOffscreen.Should().BeFalse(); } [Fact] public async Task MyControl_ShouldChangeAppearance_WhenComboBoxChanged() { // Arrange await NavigateToPage("MyControl"); var comboBox = Window.FindFirstDescendant(cf => cf.ByAutomationId("AppearanceComboBox")).AsComboBox(); var control = Window.FindFirstDescendant(cf => cf.ByAutomationId("MyControlExample")); // Act comboBox.Select(1); // Select "Secondary" await Task.Delay(100); // Assert control.Should().NotBeNull(); // Add appearance-specific assertions } [Fact] public async Task MyControl_ShouldDisable_WhenToggleSwitchUnchecked() { // Arrange await NavigateToPage("MyControl"); var toggleSwitch = Window.FindFirstDescendant(cf => cf.ByAutomationId("EnabledToggle")).AsToggleButton(); var control = Window.FindFirstDescendant(cf => cf.ByAutomationId("MyControlExample")); // Act toggleSwitch.Toggle(); await Task.Delay(100); // Assert control.IsEnabled.Should().BeFalse(); } [Fact] public async Task MyControl_ShouldExecuteCommand_WhenButtonClicked() { // Arrange await NavigateToPage("MyControl"); var button = Window.FindFirstDescendant(cf => cf.ByAutomationId("ActionButton")).AsButton(); var textBlock = Window.FindFirstDescendant(cf => cf.ByAutomationId("ResultText")).AsLabel(); // Act button.Click(); await Task.Delay(600); // Wait for async operation // Assert textBlock.Text.Should().Be("Action performed!"); } private async Task NavigateToPage(string pageName) { var navigationView = Window.FindFirstDescendant(cf => cf.ByAutomationId("NavigationView")); var menuItem = navigationView.FindFirstDescendant(cf => cf.ByName(pageName)); menuItem.Click(); await Task.Delay(500); // Wait for navigation } } ``` -------------------------------- ### Finding Control Files Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Demonstrates how the folder structure makes it easy to locate control-specific files. By navigating to the control's dedicated folder, developers can quickly find associated code and XAML. ```bash # Looking for Button control? Controls/Button/Button.cs # Immediately obvious location ``` -------------------------------- ### MVVM ViewModel Implementation Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Example of a ViewModel using CommunityToolkit.Mvvm with ObservableProperty and RelayCommand attributes. ```csharp namespace Wpf.Ui.Gallery.ViewModels.Pages.BasicInput; public partial class AnchorViewModel : ViewModel { [ObservableProperty] private bool _isAnchorEnabled = true; [RelayCommand] private void OnAnchorCheckboxChecked(object sender) { if (sender is not CheckBox checkbox) { return; } IsAnchorEnabled = !(checkbox?.IsChecked ?? false); } } ``` -------------------------------- ### MVVM Page Implementation Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Example of an MVVM Page using INavigableView and setting DataContext in the constructor. ```csharp namespace Wpf.Ui.Gallery.Views.Pages.BasicInput; [GalleryPage("Button which opens a link.", SymbolRegular.CubeLink20)] public partial class AnchorPage : INavigableView { public AnchorViewModel ViewModel { get; init; } public AnchorPage(AnchorViewModel viewModel) { ViewModel = viewModel; DataContext = this; InitializeComponent(); } } ``` -------------------------------- ### CsWin32 Configuration Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/win32-interop.md This snippet shows a sample entry in NativeMethods.txt, which is used by the CsWin32 source generator to declare Win32 functions and types needed by the library. It specifies the function signature and its return type. ```text BOOL SetWindowLongPtrW(HWND hWnd, int nIndex, LONG_PTR dwNewLong); BOOL SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, int cy, UINT uFlags); ``` -------------------------------- ### Test Namespace Mirroring Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Illustrates how source code namespaces are mirrored in the test project's namespace structure. ```text src/Wpf.Ui/Animations/TransitionAnimationProvider.cs ↓ tests/Wpf.Ui.UnitTests/Animations/TransitionAnimationProviderTests.cs ``` -------------------------------- ### Testing Services - Navigation Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Unit test pattern for testing a service, specifically a navigation service, mocking dependencies and asserting the outcome. ```csharp [Fact] public void Navigate_ReturnsTrue_WhenNavigationSucceeds() { // Arrange var pageProvider = Substitute.For(); pageProvider.GetPage(Arg.Any()).Returns(new DashboardPage()); var service = new NavigationService(pageProvider); var navigationView = Substitute.For(); service.SetNavigationControl(navigationView); // Act bool result = service.Navigate(typeof(DashboardPage)); // Assert Assert.True(result); } ``` -------------------------------- ### AwesomeAssertions Syntax Examples Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Demonstrates various assertion types including null checks, string comparisons, boolean checks, and collection assertions using the AwesomeAssertions library. ```csharp // Null checks element.Should().NotBeNull("because element must exist"); element.Should().BeNull(); // String assertions text.Should().Be("Expected"); text.Should().Contain("substring"); text.Should().StartWith("prefix"); // Boolean assertions condition.Should().BeTrue("because condition must be met"); Application?.HasExited.Should().BeTrue(); // Collection assertions items.Should().HaveCount(5); items.Should().Contain(item); ``` -------------------------------- ### Registering Navigation Services with DI Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/navigation.md Configure navigation services and page providers in your application's DI container. This example shows how to add the NavigationViewPageProvider and register pages as transient dependencies. ```csharp services.AddNavigationViewPageProvider(); services.AddSingleton(); // Pages registered in DI services.AddTransient(); services.AddTransient(); ``` -------------------------------- ### Dependency Injection Usage for SystemThemeWatcher Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/system-theme-watcher.md Start the watcher after the host is built when resolving the main window from a dependency injection container. ```csharp var host = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddHostedService(); services.AddSingleton(); // ... other services }).Build(); await host.StartAsync(); var mainWindow = host.Services.GetRequiredService(); // Watch the window after it's been created SystemThemeWatcher.Watch(mainWindow); ``` -------------------------------- ### Create a WPF UI Gallery Demo Page ViewModel Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Example ViewModel for a WPF UI Gallery demo page, showcasing observable properties, commands, and navigation lifecycle methods. Includes MIT license header and namespace conventions. ```csharp // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using System.Collections.ObjectModel; using System.Threading.Tasks; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Wpf.Ui.Controls; namespace Wpf.Ui.Gallery.ViewModels.Pages.MyCategory; public partial class MyControlViewModel : ViewModel { [ObservableProperty] private string _textValue = "Hello World"; [ObservableProperty] private bool _isEnabled = true; [ObservableProperty] private ControlAppearance _selectedAppearance = ControlAppearance.Primary; [ObservableProperty] private ObservableCollection _appearances = new() { ControlAppearance.Primary, ControlAppearance.Secondary, ControlAppearance.Success, ControlAppearance.Danger }; [RelayCommand] private void OnToggleEnabled() { IsEnabled = !IsEnabled; } [RelayCommand] private async Task OnPerformAction() { await Task.Delay(500); TextValue = "Action performed!"; } public override Task OnNavigatedToAsync() { // Called when page is navigated to return base.OnNavigatedToAsync(); } public override Task OnNavigatedFromAsync() { // Called when navigating away from page return base.OnNavigatedFromAsync(); } } ``` -------------------------------- ### Project Reference without Version Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md Example of a .csproj file referencing a NuGet package without specifying the version, relying on centralized management. ```xml all runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### Alternative Unit Test Naming Convention Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/testing.md Demonstrates the 'GivenX_Method_ExpectedResult' pattern for unit tests. Useful for setting up specific preconditions. ```csharp [Fact] public void GivenAllRegularSymbols_Swap_ReturnsValidFilledSymbol() ``` -------------------------------- ### Flat Namespace Strategy Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-002-control-library-architecture.md Illustrates the use of a flat namespace for control classes, ensuring all controls reside in `Wpf.Ui.Controls`. This simplifies XAML namespace mapping and improves intellisense. ```csharp // Physical path: Controls/Button/Button.cs namespace Wpf.Ui.Controls; // NOT Wpf.Ui.Controls.Button // ReSharper disable once CheckNamespace // Suppress warning ``` -------------------------------- ### View Setup for NavigationView Binding Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md In your MainWindow.xaml, bind the MenuItemsSource and FooterMenuItemsSource properties to the collections in your ViewModel. This example shows the XAML binding. ```xml ``` -------------------------------- ### Direct Service Instantiation Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/views/logical-architecture.md Demonstrates direct instantiation of a service for simple applications. No DI container is required. ```csharp var service = new NavigationService(); ``` -------------------------------- ### Initialize and Use a Service in ViewModel Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Demonstrates how to inject and use a service within a ViewModel, including initialization and asynchronous operation calls. Ensure the service interface is correctly implemented and injected. ```csharp public partial class MyViewModel : ViewModel { private readonly IMyService _myService; public MyViewModel(IMyService myService) { _myService = myService; _myService.Initialize("parameter-value"); } [RelayCommand] private async Task OnPerformAction() { bool result = await _myService.PerformOperationAsync(); // Handle result } } ``` -------------------------------- ### Get Current Theme Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/theming-and-appearance.md Retrieves the current application theme. ```csharp var currentTheme = ApplicationThemeManager.GetAppTheme(); ``` -------------------------------- ### Get System Accent Color Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/theming-and-appearance.md Retrieves the system accent color. ```csharp var systemAccent = ApplicationAccentColorManager.GetColorizationColor(); ``` -------------------------------- ### SymbolIcon XAML Usage Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/symbolicon.md Example of declaring a SymbolIcon control within XAML markup. ```xml ``` -------------------------------- ### Migration Strategy: Static Facade for Instance-Based ThemeManager Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Illustrates a migration path from static managers to instance-based managers. A static facade class maintains compatibility with existing code while allowing new instance-based implementations. ```csharp // New instance-based implementation public sealed class ThemeManager : IThemeManager { // Instance implementation } // Static facade maintains compatibility public static class ApplicationThemeManager { private static readonly IThemeManager _instance = new ThemeManager(); public static void Apply(ApplicationTheme theme) => _instance.Apply(theme); } ``` -------------------------------- ### Implement Service (MyService.cs) Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Create a concrete implementation of your service interface. This class will contain the actual logic for the service's operations and manage its internal state. ```csharp // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. // Copyright (C) Leszek Pomianowski and WPF UI Contributors. // All Rights Reserved. using System; using System.Threading; using System.Threading.Tasks; namespace Wpf.Ui; /// /// Implementation of . /// public partial class MyService : IMyService { private string? _parameter; private bool _isActive; /// public bool IsActive => _isActive; /// public void Initialize(string parameter) { ArgumentNullException.ThrowIfNull(parameter); _parameter = parameter; _isActive = true; } /// public async Task PerformOperationAsync(CancellationToken cancellationToken = default) { ThrowIfNotInitialized(); try { // Perform async operation await Task.Delay(100, cancellationToken); return true; } catch (OperationCanceledException) { return false; } } private void ThrowIfNotInitialized() { if (!_isActive || _parameter is null) { throw new InvalidOperationException("Service has not been initialized. Call Initialize() first."); } } } ``` -------------------------------- ### Define NavigationView in XAML Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md Basic setup for a NavigationView including MenuItems and FooterMenuItems with associated page types. ```xml ``` -------------------------------- ### Navigate from ViewModel using INavigationService Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md Inject INavigationService into any ViewModel and use it to navigate between pages. This example demonstrates navigating to the SettingsPage. ```csharp public partial class DashboardViewModel : ObservableObject { private readonly INavigationService _navigationService; public DashboardViewModel(INavigationService navigationService) { _navigationService = navigationService; } [RelayCommand] private void OnGoToSettings() { _navigationService.Navigate(typeof(SettingsPage)); } } ``` -------------------------------- ### Mocking with NSubstitute Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/TESTING-SPEC.md Illustrates how to create mocks, set return values, and verify method calls using NSubstitute. Essential for isolating dependencies in unit tests. ```csharp // Create mock UIElement element = Substitute.For(); // Setup return value INavigationService service = Substitute.For(); service.Navigate(typeof(DashboardPage)).Returns(true); // Verify call service.Received(1).Navigate(Arg.Any()); ``` -------------------------------- ### Integration Test Naming Convention Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/testing.md Shows the 'Subject_ShouldExpectedBehavior_WhenCondition' pattern for integration tests. Used for end-to-end UI automation. ```csharp [Fact] public async Task CloseButton_ShouldCloseWindow_WhenClicked() ``` -------------------------------- ### Unit Test Naming Convention Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/testing.md Illustrates the 'MethodName_ExpectedResult_WhenCondition' pattern for unit tests. Used for verifying isolated logic. ```csharp [Fact] public void ApplyTransition_ReturnsFalse_WhenDurationIsLessThan10() ``` -------------------------------- ### Simple Control Structure Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Demonstrates the basic pattern for simple controls, consisting of a single .cs file for implementation and a .xaml file for the implicit style. ```tree Badge/ ├── Badge.cs # Control implementation └── Badge.xaml # Implicit style ``` -------------------------------- ### Run Unit Tests Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/testing.md Execute all unit tests for the WPF UI project. ```bash dotnet test tests/Wpf.Ui.UnitTests/Wpf.Ui.UnitTests.csproj ``` -------------------------------- ### Set Initial Theme in App.xaml Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/themes.md Use ThemesDictionary in App.xaml to load theme resources at startup. Ensure colors and brushes are referenced as DynamicResource for theme changes to apply correctly. ```xml ``` -------------------------------- ### Mermaid Graph Diagram Syntax Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/appendix/diagrams/README.md Example of a graph diagram using Mermaid syntax. Suitable for showing relationships and flow between components. ```mermaid graph TD A[Component A] --> B[Component B] B --> C[Component C] style A fill:#e1f5e1 style B fill:#fff4e1 ``` -------------------------------- ### Mermaid Sequence Diagram Syntax Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/appendix/diagrams/README.md Example of a sequence diagram using Mermaid syntax. Useful for illustrating interactions between participants over time. ```mermaid sequenceDiagram participant A participant B A->>B: Message B-->>A: Response ``` -------------------------------- ### Run Integration Tests Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/testing.md Execute integration tests for the WPF UI Gallery application. This requires the Gallery app to be built first. ```bash dotnet test tests/Wpf.Ui.Gallery.IntegrationTests/Wpf.Ui.Gallery.IntegrationTests.csproj ``` -------------------------------- ### DI Registration for Services Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/views/logical-architecture.md Shows how to register services with a Dependency Injection container for hosted applications. This is the recommended approach for complex applications. ```csharp services.AddSingleton(); ``` -------------------------------- ### Register Services with Dependency Injection Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md Register the necessary services and pages/ViewModels with your dependency injection container. This is the first step in setting up navigation. ```csharp using Microsoft.Extensions.DependencyInjection; Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { // Main window services.AddScoped(); services.AddScoped(); // Services services.AddSingleton(); services.AddSingleton(); // Pages and ViewModels services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); }).Build(); ``` -------------------------------- ### UiApplication Class with ThreadStatic Singleton Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Implements a thread-local singleton pattern for UiApplication using [ThreadStatic]. Each UI thread gets its own instance. ```csharp public class UiApplication { [ThreadStatic] private static UiApplication? _uiApplication; public static UiApplication? Current => _uiApplication; public UiApplication(Application application) { // Stores the application reference and sets _uiApplication } // Instance methods operate on the wrapped Application public ResourceDictionary Resources => Application.Current.Resources; } ``` -------------------------------- ### Service Registration with Dependency Injection Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/views/logical-architecture.md Illustrates the integration of WPF UI services with Microsoft.Extensions.DependencyInjection using the Generic Host pattern. This is typically used in application startup to register services like navigation and content dialogs. ```mermaid sequenceDiagram participant App as Application Startup participant Host as IHostBuilder participant SC as IServiceCollection participant Ext as ServiceCollectionExtensions participant SP as IServiceProvider participant CS as ControlsServices participant NavView as NavigationView participant Provider as INavigationViewPageProvider App->>Host: Host.CreateDefaultBuilder() App->>Host: ConfigureServices(services => ...) Host->>SC: services.AddSingleton() Host->>SC: services.AddSingleton() Host->>SC: services.AddSingleton() Host->>Ext: services.AddNavigationViewPageProvider() Ext->>SC: Register INavigationViewPageProvider Host->>SC: services.AddTransient() Host->>SC: services.AddTransient() App->>Host: Build() Host->>SP: Create IServiceProvider App->>CS: ControlsServices.Initialize(serviceProvider) CS->>CS: Store IServiceProvider for control-level resolution Note over NavView,Provider: At runtime, when NavigationView needs a page: NavView->>Provider: GetPage(typeof(DashboardPage)) Provider->>SP: GetRequiredService(typeof(DashboardPage)) SP-->>Provider: DashboardPage instance Provider-->>NavView: Resolved page ``` -------------------------------- ### Mermaid Class Diagram Syntax Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/appendix/diagrams/README.md Example of a class diagram using Mermaid syntax. Used to represent classes, their attributes, methods, and relationships. ```mermaid classDiagram class Button { +Icon IconElement +Appearance ControlAppearance } Button --|> IAppearanceControl Button --|> IIconControl ``` -------------------------------- ### XML Documentation for Global Static Manager Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-004-static-managers-for-theming.md Shows the recommended XML documentation for a static manager class, emphasizing its global nature and application-wide impact. ```csharp /// /// Global theme manager. Applies themes application-wide. /// ``` -------------------------------- ### Use FontIcon in XAML Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/fonticon.md Example of how to declare and configure a FontIcon control within XAML markup, including glyph, font family, size, and foreground. ```xml ``` -------------------------------- ### Cancel Navigation Based on Conditions Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/navigation-view.md Handle the Navigating event to cancel navigation based on specific conditions. This example prevents navigation to SettingsPage if the user is not an admin. ```csharp private void OnNavigating(NavigationView sender, NavigatingCancelEventArgs args) { // Don't navigate to settings if the user is not an admin if (args.PageType == typeof(SettingsPage) && !_isAdmin) { args.Cancel = true; } } ``` -------------------------------- ### Use Win32 Interop Functions Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/IMPLEMENTATION-GUIDE.md Demonstrates three methods for using Win32 interop functions: direct P/Invoke for simple cases, a safe wrapper for validated calls, and high-level utilities for common tasks. ```csharp using Wpf.Ui.Interop; using Wpf.Ui.Win32; using Windows.Win32; using Windows.Win32.Foundation; // Option 1: Direct P/Invoke (for simple cases) int screenWidth = PInvoke.GetSystemMetrics(SYSTEM_METRICS_INDEX.SM_CXSCREEN); // Option 2: Safe wrapper (validates handle, catches exceptions) int borderWidth = UnsafeNativeMethods.GetSystemMetricSafe( windowHandle, SYSTEM_METRICS_INDEX.SM_CXBORDER ); // Option 3: High-level utility int borderHeight = Utilities.BorderHeight; ``` -------------------------------- ### Incorrect Category-Specific Namespace Example Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/decisions/ADR-005-feature-folder-controls.md Illustrates a forbidden practice of using category-specific namespaces. All control-related classes must reside within the main `Wpf.Ui.Controls` namespace. ```csharp ❌ namespace Wpf.Ui.Controls.Buttons; ``` ```csharp ✅ namespace Wpf.Ui.Controls; ``` -------------------------------- ### Enable System Theme Watching in MainWindow Constructor Source: https://github.com/lepoco/wpfui/blob/main/docs/documentation/system-theme-watcher.md Call SystemThemeWatcher.Watch(this) in your main window's constructor to automatically apply system theme, accent, and default backdrop. ```csharp using Wpf.Ui.Appearance; public partial class MainWindow : System.Windows.Window { public MainWindow() { // This will apply the system theme, accent, and default backdrop. SystemThemeWatcher.Watch(this); InitializeComponent(); } } ``` -------------------------------- ### N8 Correction: Block-Bodied Property Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/CONSTITUTION.md The corrected syntax for a property using a block body instead of an expression body, adhering to the project's style guide. ```csharp public string Name { get => _name; } ``` -------------------------------- ### Apply Theme Source: https://github.com/lepoco/wpfui/blob/main/docs/architecture/cross-cutting/theming-and-appearance.md Swaps theme resource dictionaries at runtime. Searches application-level merged dictionaries for URIs containing 'wpf.ui;' and 'theme', then replaces them with the appropriate theme file. ```csharp ApplicationThemeManager.Apply(ApplicationTheme.Dark); ```