.NET MAUI桌面应用窗口圆角设置问题求助
.NET MAUI桌面窗口圆角实现方案
因为.NET MAUI的Window类本身没有内置的CornerRadius属性,窗口样式由各操作系统原生窗口管理器控制,所以需要通过平台特定代码实现全局窗口圆角,以下是针对Windows和macOS平台的具体解决方案:
Windows平台(WinUI3)
- 利用WinUI3的
AppWindowAPI设置窗口圆角,需在窗口初始化完成后获取原生窗口实例:
protected override Window CreateWindow(IActivationState activationState) { Window window = base.CreateWindow(activationState); const int newWidth = 1000; const int newHeight = 600; window.Width = newWidth; window.Height = newHeight; window.MinimumHeight = newHeight; window.MinimumWidth = newWidth; // 监听窗口创建完成事件,确保Handler已初始化 window.Created += OnWindowCreated; return window; } private void OnWindowCreated(object sender, EventArgs e) { #if WINDOWS if (sender is Window window) { var nativeWindow = window.Handler.PlatformView as Microsoft.UI.Xaml.Window; if (nativeWindow == null) return; var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(nativeWindow); var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId); if (appWindow == null) return; // 设置圆角半径(四个角统一为10) appWindow.Presenter.SetCornerRadius(new Windows.Graphics.CornerRadius(10)); // 处理标题栏背景,避免圆角区域被纯色覆盖 nativeWindow.ExtendsContentIntoTitleBar = true; appWindow.TitleBar.BackgroundColor = Microsoft.UI.Colors.Transparent; appWindow.TitleBar.ButtonBackgroundColor = Microsoft.UI.Colors.Transparent; } #endif }
- 若不需要保留系统标题栏,可将窗口设置为无边框模式,配合自定义标题栏使用,圆角效果会更一致。
macOS平台(Mac Catalyst)
- 通过修改UIKit原生窗口的Layer属性实现圆角:
private void OnWindowCreated(object sender, EventArgs e) { #if MACCATALYST if (sender is Window window) { var nativeWindow = window.Handler.PlatformView as UIKit.UIWindow; if (nativeWindow == null) return; // 设置圆角半径 nativeWindow.Layer.CornerRadius = 10; // 确保子控件不会超出圆角边界 nativeWindow.Layer.MasksToBounds = true; // 隐藏系统默认标题栏(可选,若保留标题栏,圆角可能被标题栏遮挡) nativeWindow.TitlebarVisibility = UIKit.UIWindowTitlebarVisibility.Hidden; } #endif }
- 若需要保留标题栏,需额外调整标题栏的布局和背景,确保圆角可见。
注意事项
- 平台特定代码需通过条件编译指令(
#if WINDOWS/#if MACCATALYST)包裹,避免跨平台编译错误。 - 直接用
Border包裹页面内容仅能实现页面区域的圆角,无法修改整个操作系统窗口的圆角样式,必须通过原生窗口API调整。
内容的提问来源于stack exchange,提问作者Joao Lima
相关产品推荐
相关产品推荐

