如何在桌面端WinUI 3应用中实现窗口亚克力背景效果
WinUI 3 桌面应用窗口亚克力背景实现方案
以下方案仅适用于Windows App SDK 1.0及以上版本的WinUI 3桌面项目,不兼容UWP/WinUI 2场景
前置说明
桌面端亚克力背景仅支持Windows 11 22000及以上版本系统,Windows 10环境下DesktopAcrylicController会返回不支持,可降级使用云母效果或纯色背景。
实现步骤
- 第一步:在项目的主窗口代码文件(通常为
MainWindow.xaml.cs)顶部引入必要命名空间
using Microsoft.UI.Composition.SystemBackdrops; using Microsoft.UI.Xaml; using WinRT;
- 第二步:在主窗口类中定义私有字段
private DesktopAcrylicController _acrylicController; private SystemBackdropConfiguration _backdropConfig;
- 第三步:在主窗口构造函数的
InitializeComponent();之后调用亚克力初始化方法,方法实现如下:
private bool TryInitializeAcrylicBackdrop() { // 校验当前系统支持性 if (!DesktopAcrylicController.IsSupported()) { return false; } _backdropConfig = new SystemBackdropConfiguration(); _acrylicController = new DesktopAcrylicController(); // 绑定当前窗口为背景载体 _acrylicController.AddSystemBackdropTarget(this.As<Microsoft.UI.Composition.ICompositionSupportsSystemBackdrop>()); _acrylicController.SetSystemBackdropConfiguration(_backdropConfig); // 同步窗口激活状态 this.Activated += (s, e) => _backdropConfig.IsInputActive = true; // 窗口关闭时释放资源 this.Closed += (s, e) => { _acrylicController.Dispose(); _acrylicController = null; _backdropConfig = null; }; // 同步应用主题变更 this.ActualThemeChanged += (s, e) => { _backdropConfig.Theme = ActualTheme switch { ElementTheme.Light => SystemBackdropTheme.Light, ElementTheme.Dark => SystemBackdropTheme.Dark, _ => SystemBackdropTheme.Default }; }; return true; }
- 第四步:修改主窗口XAML配置,清除上层遮挡背景,将
MainWindow.xaml根节点的Background属性设置为Transparent,示例:
<Window x:Class="你的项目命名空间.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="Transparent"> <!-- 此处为窗口内容 --> </Window>
可选自定义配置
可通过修改DesktopAcrylicController的属性调整亚克力效果:
TintColor:调整亚克力基础色调TintOpacity:调整基础色调的不透明度LuminosityOpacity:调整背景亮度的通透程度
内容的提问来源于stack exchange,提问作者Hassaan Masood
相关产品推荐
相关产品推荐

