### Basic Window Initialization Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/System/Window.txt Demonstrates the fundamental setup for a main window in a WinUI application. This code is typically found in the App.xaml.cs file. ```csharp public partial class App : Application { public static MainWindow MainWindow = new(); public App() { this.InitializeComponent(); } protected override void OnLaunched(LaunchActivatedEventArgs args) { MainWindow.Activate(); } } ``` -------------------------------- ### Button with Image Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/Button/ButtonWithImage.txt Use this XAML to create a button that displays an image. Ensure the image source path is correct. ```XAML ``` -------------------------------- ### ColorPicker Properties Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ColorPicker/ColorPickerProperties.txt Demonstrates how to set various properties for the ColorPicker control to customize its appearance and input methods. ```xaml ``` -------------------------------- ### Basic CalendarView Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/CalendarView/BasicCalendarView.txt This XAML snippet shows a fundamental CalendarView setup. It configures selection mode, visibility of group labels and out-of-scope dates, and specifies language and calendar identifier. ```xaml ``` -------------------------------- ### Start Media Capture Preview Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Media/CaptureElementPreviewSample_cs.txt Initializes MediaCapture with a specified camera device group and sets the CaptureElement's source to display the preview. Ensure you have a camera device available. ```C# using Windows.Media.Capture.Frames; using Windows.Media.Capture; private MediaFrameSourceGroup mediaFrameSourceGroup; private MediaCapture mediaCapture; async private void StartCaptureElement() { var groups = await MediaFrameSourceGroup.FindAllAsync(); if (groups.Count == 0) { frameSourceName.Text = "No camera devices found."; return; } mediaFrameSourceGroup = groups.First(); frameSourceName.Text = "Viewing: " + mediaFrameSourceGroup.DisplayName; mediaCapture = new MediaCapture(); var mediaCaptureInitializationSettings = new MediaCaptureInitializationSettings() { SourceGroup = this.mediaFrameSourceGroup, SharingMode = MediaCaptureSharingMode.SharedReadOnly, StreamingCaptureMode = StreamingCaptureMode.Video, MemoryPreference = MediaCaptureMemoryPreference.Cpu }; await mediaCapture.InitializeAsync(mediaCaptureInitializationSettings); // Set the MediaPlayerElement's Source property to the MediaSource for the mediaCapture. var frameSource = mediaCapture.FrameSources[this.mediaFrameSourceGroup.SourceInfos[0].Id]; captureElement.Source = Windows.Media.Core.MediaSource.CreateFromMediaFrameSource(frameSource); $(MirrorPreview) } ``` -------------------------------- ### Starting Connected Animation on Detail Page Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ConnectedAnimation/ConnectedAnimationListPage.txt This snippet shows how to retrieve and start a 'forward' connected animation when the detail page is navigated to. It also handles coordinated animations with other UI elements. ```C# protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // Store the item to be used in binding to UI DetailedObject = e.Parameter as CustomDataObject; ConnectedAnimation imageAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation"); if (imageAnimation != null) { // Connected animation + coordinated animation imageAnimation.TryStart(detailedImage, new UIElement[] { coordinatedPanel }); } } ``` -------------------------------- ### Start Animation on Destination Page Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ConnectedAnimation/SimpleConnectedAnimation.txt Retrieves and starts the connected animation after navigating to the destination page. Handles cases where the animation might not be available. ```csharp protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation"); if (anim != null) { anim.TryStart(DestinationElement); } } ``` -------------------------------- ### Basic Lottie Animation Playback Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/AnimatedVisualPlayer/AnimatedVisualPlayerPlaybackLottieAnimation.txt Use this XAML to configure an AnimatedVisualPlayer to host and control a Lottie animation. Set AutoPlay to False to manually control playback. ```xaml ``` -------------------------------- ### Start Connected Animation for Backward Navigation Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample4_cs.txt In the OnNavigatedTo method, retrieve the animation using ConnectedAnimationService.GetAnimation() and attempt to start it on the target element. This is used when returning from a detail page to restore the visual connection. ```csharp protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (_storedItem == null) return; // Restore scroll position so the target element is visible. scrollViewer.ChangeView(null, _persistedScrollPosition, null, true); UpdateLayout(); var animation = ConnectedAnimationService.GetForCurrentView() .GetAnimation("BackConnectedAnimation"); if (animation != null) { animation.Configuration = new DirectConnectedAnimationConfiguration(); int index = repeater.ItemsSourceView.IndexOf(_storedItem); if (repeater.TryGetElement(index) is FrameworkElement container && FindChildByName(container, "connectedElement") is UIElement target) { animation.TryStart(target); } } } ``` -------------------------------- ### Deploy WinUI 3 Gallery Package Source: https://github.com/microsoft/winui-gallery/blob/main/tests/WinUIGallery.UITests/README.md Deploy the generated WinUI 3 Gallery package for testing using the provided installation script. ```powershell PS> .\WinUIGallery\AppxPackages\WinUIGallery_Test\Install.ps1 ``` -------------------------------- ### Initiate Forward Connected Animation Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample2_cs.txt Prepares and starts a forward connected animation when navigating from a collection to a detail view. It sets up the animation and updates the detail content. ```csharp private void TipsGrid_ItemClick(object sender, ItemClickEventArgs e) { ConnectedAnimation? animation = null; if (collection.ContainerFromItem(e.ClickedItem) is GridViewItem container) { _storedItem = container.Content as CustomDataObject; animation = collection.PrepareConnectedAnimation("forwardAnimation", _storedItem, "connectedElement"); } // Update the detail view with the clicked item's data. if (_storedItem != null) { detailImage.Source = new BitmapImage(new Uri("ms-appx://" + _storedItem.ImageLocation)); detailTitle.Text = _storedItem.Title; detailDescription.Text = _storedItem.Description; } SmokeGrid.Visibility = Visibility.Visible; animation?.TryStart(destinationElement); } ``` -------------------------------- ### C# ViewModel and Page Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/Binding/BindingViewModel.txt This C# code sets up a WinUI Page and a ViewModel. The ViewModel implements INotifyPropertyChanged to enable data binding, and the Page sets its DataContext to an instance of the ViewModel. ```csharp using System.ComponentModel; // For INotifyPropertyChanged interface. using Microsoft.UI.Xaml.Controls; // For Page and other WinUI controls. namespace YourNamespace { // Main page class public sealed partial class YourPage : Page { // Property to hold the ViewModel instance. public ExampleViewModel ViewModel { get; set; } public YourPage() { this.InitializeComponent(); // Initialize the ViewModel with sample data. ViewModel = new ExampleViewModel { Title = "Welcome to WinUI 3", // Set initial value for Title. Description = "This is an example of binding to a view model.", // Set initial value for Description. }; // Set the DataContext of the page to the ViewModel. // This makes the ViewModel properties available for binding in XAML. DataContext = ViewModel; } } // ViewModel class implementing INotifyPropertyChanged for data binding. public class ExampleViewModel : INotifyPropertyChanged { // Backing field for Title property. private string _title = string.Empty; // Backing field for Description property. private string _description = string.Empty; // Property for Title with change notification. public string Title { get => _title; // Return the current value of _title. set { if (_title != value) // Check if the new value is different. { _title = value; // Update the backing field. OnPropertyChanged(nameof(Title)); // Notify the UI of the change. } } } // Property for Description with change notification. public string Description { get => _description; // Return the current value of _description. set { if (_description != value) // Check if the new value is different. { _description = value; // Update the backing field. OnPropertyChanged(nameof(Description)); // Notify the UI of the change. } } } // Event to notify subscribers (UI elements) of property changes. public event PropertyChangedEventHandler? PropertyChanged; // Method to raise the PropertyChanged event. // This notifies the UI to update the bound control. protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ``` -------------------------------- ### VariableSizedWrapGrid Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/VariableSizedWrapGrid/VariablesizedwrapgridControl.txt Demonstrates how to configure a VariableSizedWrapGrid with specific orientations, maximum rows/columns, and item dimensions. Shows how to use attached properties like RowSpan and ColumnSpan to control item layout. ```XAML ``` -------------------------------- ### InfoBadge Styles Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/InfoBadge/DifferentInfobadgeStyles.txt Shows how to apply different predefined styles to InfoBadge controls. Use $(Style)IconInfoBadgeStyle for icon-based badges, $(Style)ValueInfoBadgeStyle for badges displaying a numerical value, and $(Style)DotInfoBadgeStyle for simple dot indicators. ```XAML ``` -------------------------------- ### TreeView Data Binding Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/TreeView/TreeViewDataBindingSample_cs.txt Initializes the TreeView's data source with sample hierarchical data and sets the DataContext for binding. This code defines the structure of the data that will be displayed in the TreeView. ```csharp using System.Collections.ObjectModel; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; namespace YourNamespace { public sealed partial class YourPage : Page { // DataSource is the data collection that will be bound to the TreeView's ItemsSource. public ObservableCollection DataSource { get; set; } public YourPage() { this.InitializeComponent(); // Initialize the data source with sample data and set it as the context for data binding. DataSource = GetData(); this.DataContext = this; // Bind the DataContext of the page to itself for XAML bindings. } // Method to provide sample data for the TreeView. private ObservableCollection GetData() { return new ObservableCollection { // Root folder with child files. new ExplorerItem { Name = "Documents", Type = ExplorerItem.ExplorerItemType.Folder, Children = { new ExplorerItem { Name = "ProjectProposal", Type = ExplorerItem.ExplorerItemType.File, }, new ExplorerItem { Name = "BudgetReport", Type = ExplorerItem.ExplorerItemType.File, }, }, }, // Another root folder with one child file. new ExplorerItem { Name = "Projects", Type = ExplorerItem.ExplorerItemType.Folder, Children = { new ExplorerItem { Name = "Project Plan", Type = ExplorerItem.ExplorerItemType.File, }, }, }, }; } } // Class to represent items in the TreeView. public class ExplorerItem { // Enum to define the type of the item: Folder or File. public enum ExplorerItemType { Folder, File, } // Name of the item (displayed in the TreeView). public string Name { get; set; } = string.Empty; // Type of the item (Folder or File). public ExplorerItemType Type { get; set; } // Collection of child items. Used for nested nodes in the TreeView. public ObservableCollection Children { get; set; } = new ObservableCollection(); } } ``` -------------------------------- ### TextBlock Properties Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/TextBlock/TextblockVariousProperties.txt This XAML snippet shows how to set properties like Text, FontFamily, FontSize, FontStyle, TextWrapping, CharacterSpacing, and Foreground for a TextBlock. ```XAML ``` -------------------------------- ### Basic Pivot Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/Pivot/BasicPivot.txt Use this XAML structure to create a Pivot control with a title and several items. Each PivotItem can contain any UI content. ```xaml ``` -------------------------------- ### Preparing Forward Connected Animation Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ConnectedAnimation/ConnectedAnimationListPage.txt This code prepares a 'forward' connected animation when an item in a collection is clicked. It stores the clicked item and prepares the animation to be started on the next page. ```C# private void collection_ItemClick(object sender, ItemClickEventArgs e) { // Get the collection item corresponding to the clicked item. if (collection.ContainerFromItem(e.ClickedItem) is ListViewItem container) { // Stash the clicked item for use later. We'll need it when we connect back from the detailpage. _storeditem = container.Content as CustomDataObject; // Prepare the connected animation. // Notice that the stored item is passed in, as well as the name of the connected element. // The animation will actually start on the Detailed info page. collection.PrepareConnectedAnimation("ForwardConnectedAnimation", _storeditem, "connectedElement"); } // Navigate to the DetailedInfoPage. // Note that we suppress the default animation. Frame.Navigate(typeof(DetailedInfoPage), _storeditem, new SuppressNavigationTransitionInfo()); } ``` -------------------------------- ### Basic AutoSuggestBox XAML Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/AutoSuggestBox/BasicAutosuggestBox.txt This XAML defines an AutoSuggestBox with event handlers for text changes and suggestion selection. It also sets a width and an automation property name. ```XAML ``` -------------------------------- ### Playing Back Connected Animation Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ConnectedAnimation/ConnectedAnimationListPage.txt This snippet shows how to retrieve and start a 'back' connected animation when returning to a list page. It includes logic to set up a direct connected animation configuration if the API is available. ```C# private async void collection_Loaded(object sender, RoutedEventArgs e) { if (_storeditem != null) { // If the connected item appears outside the viewport, scroll it into view. collection.ScrollIntoView(_storeditem, ScrollIntoViewAlignment.Default); collection.UpdateLayout(); // Play the second connected animation. ConnectedAnimation animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("BackConnectedAnimation"); if (animation != null) { // Setup the "back" configuration if the API is present. if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 7)) { animation.Configuration = new DirectConnectedAnimationConfiguration(); } await collection.TryStartConnectedAnimationAsync(animation, _storeditem, "connectedElement"); } // Set focus on the list collection.Focus(FocusState.Programmatic); } } ``` -------------------------------- ### Detailed Page Logic Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample1_cs.txt Handles navigation to the detailed view, starts the forward connected animation, and prepares the back animation when navigating away. It also manages focus on the back button. ```C# // DETAILED PAGE public sealed partial class DetailedInfoPage : Page { public CustomDataObject? DetailedObject { get; set; } public DetailedInfoPage() { this.InitializeComponent(); GoBackButton.Loaded += GoBackButton_Loaded; } private void GoBackButton_Loaded(object sender, RoutedEventArgs e) { // When we land in page, put focus on the back button GoBackButton.Focus(FocusState.Programmatic); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // Store the item to be used in binding to UI DetailedObject = e.Parameter as CustomDataObject; ConnectedAnimation imageAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation"); if (imageAnimation != null) { // Connected animation + coordinated animation imageAnimation.TryStart(detailedImage, new UIElement[] { coordinatedPanel }); } } // Create connected animation back to collection page. protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("BackConnectedAnimation", detailedImage); } private void BackButton_Click(object sender, RoutedEventArgs e) { Frame.GoBack(); } } ``` -------------------------------- ### Basic NavigationView Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/NavigationView/NavigationViewSample6.txt This XAML defines a NavigationView with a few menu items and a Frame for content. The PaneDisplayMode is set to Auto, allowing the control to adapt to different screen sizes. The SelectionChanged event is handled to manage navigation. ```xaml ``` -------------------------------- ### Start Animation on Destination Page Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/ConnectedAnimation/ConnectedAnimationSample3_cs.txt Retrieves and starts the 'ForwardConnectedAnimation' on the DestinationElement after navigating to the destination page. This should be called within the OnNavigatedTo method. ```csharp // Start animation on Destination page protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("ForwardConnectedAnimation"); if (anim != null) { anim.TryStart(DestinationElement); } } ``` -------------------------------- ### Initialize ItemsRepeater with Data Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample3_cs.txt Sets up the ItemsRepeater by providing a list of strings as its data source and subscribing to the ElementPrepared event for virtualization. ```csharp private double AnimatedBtnHeight; private Microsoft.UI.Xaml.Thickness AnimatedBtnMargin; private void InitializeData() { IList colors = new List() { "Blue", "BlueViolet", "Crimson", "DarkCyan", "DarkGoldenrod", "DarkMagenta", "DarkOliveGreen", "DarkRed", "DarkSlateBlue", "DeepPink", "IndianRed", "MediumSlateBlue", "Maroon", "MidnightBlue", "Peru", "SaddleBrown", "SteelBlue", "OrangeRed", "Firebrick", "DarkKhaki" }; animatedScrollRepeater.ItemsSource = colors; animatedScrollRepeater.ElementPrepared += OnElementPrepared; } ``` -------------------------------- ### Setting up Mica Backdrop Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SystemBackdrops/SystemBackdropsMicacontroller.txt This function attempts to enable the Mica backdrop for the window. It checks for support, configures the SystemBackdropConfiguration, and initializes the MicaController. ```csharp using System.Runtime.InteropServices; using WinRT; using Microsoft.UI.Composition; using Microsoft.UI.Composition.SystemBackdrops; MicaController micaController; SystemBackdropConfiguration configurationSource; bool TrySetMicaBackdrop(bool useMicaAlt) { if (MicaController.IsSupported()) { DispatcherQueue.EnsureSystemDispatcherQueue(); // Hooking up the policy object configurationSource = new SystemBackdropConfiguration(); Activated += Window_Activated; Closed += Window_Closed; ((FrameworkElement)Content).ActualThemeChanged += Window_ThemeChanged; // Initial configuration state. configurationSource.IsInputActive = true; SetConfigurationSourceTheme(); micaController = new MicaController(); micaController.Kind = useMicaAlt ? MicaKind.BaseAlt : MicaKind.Base; // Enable the system backdrop. micaController.AddSystemBackdropTarget(this.As()); micaController.SetSystemBackdropConfiguration(configurationSource); return true; // Succeeded. } return false; // Mica is not supported on this system. } private void Window_Activated(object sender, WindowActivatedEventArgs args) { configurationSource.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated; } private void Window_Closed(object sender, WindowEventArgs args) { // Make sure any Mica/Acrylic controller is disposed if (micaController != null) { micaController.Dispose(); micaController = null; } this.Activated -= Window_Activated; configurationSource = null; } private void Window_ThemeChanged(FrameworkElement sender, object args) { if (configurationSource != null) { SetConfigurationSourceTheme(); } } private void SetConfigurationSourceTheme() { switch (((FrameworkElement)Content).ActualTheme) { case ElementTheme.Dark: configurationSource.Theme = SystemBackdropTheme.Dark; break; case ElementTheme.Light: configurationSource.Theme = SystemBackdropTheme.Light; break; case ElementTheme.Default: configurationSource.Theme = SystemBackdropTheme.Default; break; } } ``` -------------------------------- ### Build and Publish WinUI 3 Gallery Source: https://github.com/microsoft/winui-gallery/blob/main/tests/WinUIGallery.UITests/README.md Build and publish the WinUI 3 Gallery application from the command line. Ensure the AppxPackageDir and PublishProfile are correctly set. ```powershell >dotnet.exe publish WinUIGallery.slnx /p:AppxPackageDir=AppxPackages\ /p:platform=x64 /p:PublishProfile=./WinUIGallery/Properties/PublishProfiles/win-x64.pubxml ``` -------------------------------- ### Start Spring Animation on Pointer Enter Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt This snippet demonstrates how to trigger a spring animation to scale up an element when the pointer enters it. It calls CreateOrUpdateSpringAnimation to set the final scale to 1.5 and then starts the animation. ```C# private void element_PointerEntered(object sender, PointerRoutedEventArgs e) { // Scale up to 1.5 CreateOrUpdateSpringAnimation(1.5f); (sender as UIElement)?.StartAnimation(_springAnimation); } ``` -------------------------------- ### Data Initialization Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/ItemsRepeater/ItemsRepeaterSample4_cs.txt Creates and populates a list of Recipe objects, assigning random ingredients and properties. ```C# public MyItemsSource filteredRecipeData = new MyItemsSource(null); public List staticRecipeData; private void InitializeData() { // ... // Create a list of Recipe objects, initializing each of them with a random number, // correlating name, and random color to associate with it. var rnd = new Random(); List tempList = new List( Enumerable.Range(0, 1000).Select(k => new Recipe { Num = k, Name = "Recipe " + k.ToString(), Color = colors[k % 15 + 1] })); // The lists fruits, vegetables, grains, and proteins were all populated with strings. // This loop goes through each Recipe item and populates its ingredients list with one // string from each list/category, then randomizes the ingredients list by adding extras. foreach (Recipe rec in tempList) { string fruitOption = fruits[rnd.Next(0, 6)]; string vegOption = vegetables[rnd.Next(0, 6)]; string grainOption = grains[rnd.Next(0, 6)]; string proteinOption = proteins[rnd.Next(0, 6)]; rec.Ingredients = "\n" + fruitOption + "\n" + vegOption + "\n" + grainOption + "\n" + proteinOption; rec.IngList = new List() { fruitOption, vegOption, grainOption, proteinOption }; rec.RandomizeIngredients(); } } ``` -------------------------------- ### TrySetAcrylicBackdrop Method Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/SystemBackdrops/SystemBackdropsSampleDesktopAcrylicController.txt This method attempts to set up and enable the Desktop Acrylic system backdrop. It checks for support, initializes the configuration, creates the controller, and adds it as a backdrop target. Ensure DispatcherQueue is initialized. ```C# using System.Runtime.InteropServices; using WinRT; using Microsoft.UI.Composition; using Microsoft.UI.Composition.SystemBackdrops; SystemBackdrops.DesktopAcrylicController acrylicController; SystemBackdrops.SystemBackdropConfiguration configurationSource; bool TrySetAcrylicBackdrop(bool useAcrylicThin) { if (DesktopAcrylicController.IsSupported()) { DispatcherQueue.EnsureSystemDispatcherQueue(); // Hooking up the policy object configurationSource = new SystemBackdropConfiguration(); Activated += Window_Activated; Closed += Window_Closed; ((FrameworkElement)Content).ActualThemeChanged += Window_ThemeChanged; // Initial configuration state. configurationSource.IsInputActive = true; SetConfigurationSourceTheme(); acrylicController = new DesktopAcrylicController(); acrylicController.Kind = useAcrylicThin ? DesktopAcrylicKind.Thin : DesktopAcrylicKind.Base; // Enable the system backdrop. acrylicController.AddSystemBackdropTarget(As()); acrylicController.SetSystemBackdropConfiguration(configurationSource); return true; // Succeeded. } return false; // Acrylic is not supported on this system. } private void Window_Activated(object sender, WindowActivatedEventArgs args) { configurationSource.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated; } private void Window_Closed(object sender, WindowEventArgs args) { // Make sure any Mica/Acrylic controller is disposed if (acrylicController != null) { acrylicController.Dispose(); acrylicController = null; } Activated -= Window_Activated; configurationSource = null; } private void Window_ThemeChanged(FrameworkElement sender, object args) { if (configurationSource != null) { SetConfigurationSourceTheme(); } } private void SetConfigurationSourceTheme() { switch (((FrameworkElement)this.Content).ActualTheme) { case ElementTheme.Dark: configurationSource.Theme = SystemBackdropTheme.Dark; break; case ElementTheme.Light: configurationSource.Theme = SystemBackdropTheme.Light; break; case ElementTheme.Default: configurationSource.Theme = SystemBackdropTheme.Default; break; } } ``` -------------------------------- ### Start Spring Animation on Pointer Exit Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Motion/AnimationInterop/AnimationInteropSample1_cs.txt This snippet shows how to revert an element's scale to its original size when the pointer exits. It calls CreateOrUpdateSpringAnimation to set the final scale to 1.0 and then starts the animation. ```C# private void element_PointerExited(object sender, PointerRoutedEventArgs e) { // Scale back down to 1.0 CreateOrUpdateSpringAnimation(1.0f); (sender as UIElement)?.StartAnimation(_springAnimation); } ``` -------------------------------- ### XAML for Formatted NumberBox Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/NumberBox/FormattedNumberboxRoundsNearest.txt Defines a NumberBox with a header and placeholder text. This XAML is the visual setup for the component. ```xaml ``` -------------------------------- ### Initialize MediaCapture and Set MediaPlayerElement Source Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/CaptureElementPreview/CaptureElementPreviewMediacapturePreviewDisplayedVia.txt Initializes MediaCapture with the selected camera and sets the MediaPlayerElement's source to the media frame source. Ensure MediaCaptureInitializationSettings are correctly configured. ```C# using Windows.Media.Capture.Frames; using Windows.Media.Capture; private MediaFrameSourceGroup mediaFrameSourceGroup; private MediaCapture mediaCapture; async private void StartCaptureElement() { var groups = await MediaFrameSourceGroup.FindAllAsync(); if (groups.Count == 0) { frameSourceName.Text = "No camera devices found."; return; } mediaFrameSourceGroup = groups.First(); frameSourceName.Text = "Viewing: " + mediaFrameSourceGroup.DisplayName; mediaCapture = new MediaCapture(); var mediaCaptureInitializationSettings = new MediaCaptureInitializationSettings() { SourceGroup = this.mediaFrameSourceGroup, SharingMode = MediaCaptureSharingMode.SharedReadOnly, StreamingCaptureMode = StreamingCaptureMode.Video, MemoryPreference = MediaCaptureMemoryPreference.Cpu }; await mediaCapture.InitializeAsync(mediaCaptureInitializationSettings); // Set the MediaPlayerElement's Source property to the MediaSource for the mediaCapture. var frameSource = mediaCapture.FrameSources[this.mediaFrameSourceGroup.SourceInfos[0].Id]; captureElement.Source = Windows.Media.Core.MediaSource.CreateFromMediaFrameSource(frameSource); $(MirrorPreview) } ``` -------------------------------- ### Define BreadcrumbBar in XAML Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/BreadcrumbBar/BreadcrumbbarControl.txt Defines a basic BreadcrumbBar control using XAML. No specific setup is required beyond this declaration. ```xaml ``` -------------------------------- ### Run WinAppDriver Manually Source: https://github.com/microsoft/winui-gallery/blob/main/tests/WinUIGallery.UITests/README.md Manually launch WinAppDriver to observe diagnostic output. Ensure WinAppDriver is installed from the official releases. ```powershell >C:\Program Files (x86)\Windows Application Driver\WinAppDriver.exe ``` -------------------------------- ### ItemsRepeater Initialization and Data Binding (C#) Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ItemsRepeater/ItemsRepeaterAnimatedScrollingContentDisplay.txt Initializes the ItemsRepeater with a list of colors and sets up event handlers for element preparation. This is necessary for virtualization. ```C# // Initialization code private double AnimatedBtnHeight; private Microsoft.UI.Xaml.Thickness AnimatedBtnMargin; private void InitializeData() { IList colors = new List() { "Blue", "BlueViolet", "Crimson", "DarkCyan", "DarkGoldenrod", "DarkMagenta", "DarkOliveGreen", "DarkRed", "DarkSlateBlue", "DeepPink", "IndianRed", "MediumSlateBlue", "Maroon", "MidnightBlue", "Peru", "SaddleBrown", "SteelBlue", "OrangeRed", "Firebrick", "DarkKhaki" }; animatedScrollRepeater.ItemsSource = colors; animatedScrollRepeater.ElementPrepared += OnElementPrepared; } ``` -------------------------------- ### Get Selected Index from Viewport Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ItemsRepeater/ItemsRepeaterAnimatedScrollingContentDisplay.txt Calculates the index of the item currently centered in the viewport. This is useful for determining which item is most visible. ```C# private int GetSelectedIndexFromViewport() { int selectedItemIndex = (int)Math.Floor(CenterPointOfViewportInExtent() / ((double)AnimatedBtnMargin.Top + AnimatedBtnHeight)); selectedItemIndex %= animatedScrollRepeater.ItemsSourceView.Count; return selectedItemIndex; } ``` -------------------------------- ### Open Teaching Tip Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/TeachingTip/TeachingTipSample2_cs.txt Use the IsOpen property to programmatically show or hide a Teaching Tip. This is useful for scenarios where the tip should appear based on user actions or application state. ```C# private void TestButton2Click(object sender, RoutedEventArgs e) { TestButton2TeachingTip.IsOpen = true; } ``` -------------------------------- ### StackPanel as ListView ItemsPanel Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/Templates/TemplatesSample3_StackPanel_xaml.txt Use a StackPanel within an ItemsPanelTemplate to define the layout of ListView items. This example arranges items vertically. ```xaml Item 01 Item 02 Item 20 ``` -------------------------------- ### Open Teaching Tip Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/TeachingTip/TeachingTipSample3_cs.txt Use this C# code to open a Teaching Tip by setting its IsOpen property to true. Ensure the Teaching Tip is defined in XAML. ```C# private void TestButton3Click(object sender, RoutedEventArgs e) { TestButton3TeachingTip.IsOpen = true; } ``` -------------------------------- ### DropDownButton with Icons Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/DropDownButton/DropDownButtonIcon.txt This XAML defines a DropDownButton. The button itself displays an icon, and its flyout contains menu items, each with an associated icon. ```XAML ``` -------------------------------- ### Get Selected Item from Viewport Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ItemsRepeater/ItemsRepeaterAnimatedScrollingContentDisplay.txt Retrieves the UI element (a Button in this case) that is currently centered in the viewport by first finding its index. ```C# // Return item that's at the center of the viewport. private object? GetSelectedItemFromViewport() { var selectedIndex = GetSelectedIndexFromViewport(); var selectedElement = animatedScrollRepeater.TryGetElement(selectedIndex) as Button; return selectedElement; } ``` -------------------------------- ### Using StaticResource for Brushes Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/XamlResources/XamlResourcesSample2_xaml.txt StaticResource uses the value defined when the app starts and does not update when the theme changes. This is suitable for resources that should remain constant. ```XAML ``` -------------------------------- ### Build UITests Source: https://github.com/microsoft/winui-gallery/blob/main/tests/WinUIGallery.UITests/README.md Build the UI tests project using either dotnet build or msbuild. This prepares the test executables. ```shell >dotnet build WinUIGallery.slnx --or-- >msbuild WinUIGallery.slnx ``` -------------------------------- ### ScrollView and AnnotatedScrollBar XAML Setup Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/AnnotatedScrollBar/AnnotatedscrollbarLinkedScrollview.txt Defines the ScrollView and AnnotatedScrollBar elements in XAML. The ScrollView's vertical scroll controller will be linked to the AnnotatedScrollBar. ```xaml ``` -------------------------------- ### Open Media File with FileOpenPicker Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/MediaPlayerElement/MediaplayerelementTransportControls.txt Handles opening a media file using FileOpenPicker and setting it as the MediaPlayerElement source. Requires the XamlRoot to initialize the picker. ```csharp private async void OpenFileButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) { var picker = new FileOpenPicker((sender as Button).XamlRoot.ContentIslandEnvironment.AppWindowId); var file = await picker.PickSingleFileAsync(); if (file == null) return; var mediaSource = MediaSource.CreateFromStorageFile(await StorageFile.GetFileFromPathAsync(file.Path)); Player1.Source = mediaSource; } ``` -------------------------------- ### Initialize AppWindow Properties Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/AppWindow/CreatingCustomizingAppwindowWindow.txt Sets the window title, size, position, and taskbar/title bar icons when initializing a Window. Ensure the icon file path is correct. ```csharp using Microsoft.UI.Windowing; using Microsoft.UI.Xaml; namespace YourNamespace; public sealed partial class SampleWindow1 : Window { public SampleWindow1() { this.InitializeComponent(); // Set the window title AppWindow.Title = "$(WindowTitle)"; // Set the window size (including borders) AppWindow.Resize(new Windows.Graphics.SizeInt32($(Width), $(Height))); // Set the window position on screen AppWindow.Move(new Windows.Graphics.PointInt32($(X), $(Y))); // Set the taskbar icon (displayed in the taskbar) AppWindow.SetTaskbarIcon("Assets/Tiles/GalleryIcon.ico"); // Set the title bar icon (displayed in the window's title bar) AppWindow.SetTitleBarIcon("Assets/Tiles/GalleryIcon.ico"); // Set the window icon (affects both taskbar and title bar, can be omitted if the above two are set) // AppWindow.SetIcon("Assets/Tiles/GalleryIcon.ico"); AppWindow.TitleBar.PreferredTheme = TitleBarTheme.UseDefaultAppMode; } private void Show_Click(object sender, RoutedEventArgs e) { AppWindow.Hide(); Task.Delay(3000).ContinueWith(t => AppWindow.Show()); } private void Hide_Click(object sender, RoutedEventArgs e) { AppWindow.Hide(); } private void Close_Click(object sender, RoutedEventArgs e) { this.Close(); } } ``` -------------------------------- ### NavigationView Default PaneDisplayMode Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/NavigationView/NavigationviewDefaultPanedisplaymode.txt This XAML defines a NavigationView with several menu items and a Frame for content. It showcases the default PaneDisplayMode behavior. ```xaml ``` -------------------------------- ### Configuring GridView ItemsWrapGrid Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/GridView/GridviewLayoutCustomization.txt Customize the behavior of the ItemsWrapGrid panel within a GridView. This example sets the maximum number of items before wrapping and the orientation. ```XAML ``` -------------------------------- ### Using CounterControl in XAML Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/CustomUserControls/CustomUserControlsCounterControlIncrementDecrement.txt Shows how to instantiate and use the custom CounterControl in a page's XAML. Different instances can be configured with distinct modes. ```xaml ``` -------------------------------- ### Initialize and Populate Recipe Data Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/ItemsRepeater/ItemsRepeaterVirtualizedContentHeavyLayout.txt This code initializes a list of Recipe objects with random ingredients and colors. It then populates a custom ItemsSource and a static list for filtering and sorting purposes. The ItemsSource is set for the ItemsRepeater. ```C# public MyItemsSource filteredRecipeData = new MyItemsSource(null); public List staticRecipeData; private void InitializeData() { // ... // Create a list of Recipe objects, initializing each of them with a random number, // correlating name, and random color to associate with it. var rnd = new Random(); List tempList = new List( Enumerable.Range(0, 1000).Select(k => new Recipe { Num = k, Name = "Recipe " + k.ToString(), Color = colors[k % 15 + 1] })); // The lists fruits, vegetables, grains, and proteins were all populated with strings. // This loop goes through each Recipe item and populates its ingredients list with one // string from each list/category, then randomizes the ingredients list by adding extras. foreach (Recipe rec in tempList) { string fruitOption = fruits[rnd.Next(0, 6)]; string vegOption = vegetables[rnd.Next(0, 6)]; string grainOption = grains[rnd.Next(0, 6)]; string proteinOption = proteins[rnd.Next(0, 6)]; rec.Ingredients = "\n" + fruitOption + "\n" + vegOption + "\n" + grainOption + "\n" + proteinOption; rec.IngList = new List() { fruitOption, vegOption, grainOption, proteinOption }; rec.RandomizeIngredients(); } // The custom MyItemsSource object, filteredRecipeData, is initialized. filteredRecipeData.InitializeCollection(tempList); // A static list of the original recipe data is saved to use for filtering. staticRecipeData = new List(tempList); // The ItemsSource is set for the ItemsRepeater created in the XAML file. VariedImageSizeRepeater.ItemsSource = filteredRecipeData; // ... } ``` -------------------------------- ### C# Implementation of CompactOverlayPresenter Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/AppWindow/AppwindowCompactoverlaypresenter.txt This C# code demonstrates how to create and apply a CompactOverlayPresenter to an AppWindow. It sets the window icon, preferred title bar theme, and configures the initial size for the compact overlay mode. ```csharp using Microsoft.UI.Windowing; using Microsoft.UI.Xaml; namespace YourNamespace; public sealed partial class SampleWindow7 : Window { public SampleWindow7(string InitialSize) { this.InitializeComponent(); AppWindow.SetIcon("Assets/Tiles/GalleryIcon.ico"); AppWindow.TitleBar.PreferredTheme = TitleBarTheme.UseDefaultAppMode; // Creates a CompactOverlay (Picture-in-Picture) presenter CompactOverlayPresenter presenter = CompactOverlayPresenter.Create(); // Sets the initial size of the CompactOverlay window presenter.InitialSize = CompactOverlaySize.$(InitialSize); // Applies the CompactOverlay presenter to the window AppWindow.SetPresenter(presenter); } } ``` -------------------------------- ### Cascading MenuFlyout Example Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/MenuFlyout/MenuflyoutCascadingMenus.txt This XAML defines a button with a flyout menu that includes cascading sub-menus. Use MenuFlyoutSubItem to create nested menu structures. ```xaml ``` -------------------------------- ### Get Available Clipboard Formats Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/Clipboard/OtherClipboardOperations.txt Retrieves the content of the clipboard and iterates through its available formats. This is useful for determining what data types are currently available for pasting. ```csharp var package = Clipboard.GetContent(); foreach (var format in package.AvailableFormats) { // Display each format } ``` -------------------------------- ### Run Test Cases from Command Line Source: https://github.com/microsoft/winui-gallery/blob/main/tests/WinUIGallery.UITests/README.md Execute the built test cases from the command line using either dotnet test or vstest.console.exe. Specify the correct path to the test DLL. ```shell >dotnet test .\WinUIGallery\WinUIGallery.UITests.csproj --or-- >vstest.console.exe .\WinUIGallery.UITests\bin\x64\Debug\net7.0\WinUIGallery.UITests.dll ``` -------------------------------- ### Configure Desktop Acrylic Backdrop Source: https://github.com/microsoft/winui-gallery/blob/main/WinUIGallery/Samples/SampleCode/SystemBackdrops/SystemBackdropsSampleBackdropTypes_cs.txt Applies a Desktop Acrylic backdrop to the window. Checks for Desktop Acrylic support before applying. ```C# bool TrySetDesktopAcrylicBackdrop() { if (DesktopAcrylicController.IsSupported()) { DesktopAcrylicBackdrop DesktopAcrylicBackdrop = new DesktopAcrylicBackdrop(); SystemBackdrop = DesktopAcrylicBackdrop; return true; // Succeeded. } return false; // DesktopAcrylic is not supported on this system. } ```