.NET 9.0 MAUI应用如何设置内容页面大小?
.NET 9 MAUI 固定窗口尺寸的替代方案
在.NET 9的MAUI中,App类不再继承自Application,而是基于MauiApp构建,因此无法再通过重写CreateWindow方法来设置窗口尺寸。以下是两种可行的替代方案:
方案一:在MauiProgram.cs中全局配置窗口默认尺寸
这是全局统一窗口大小的最优方式,直接在应用启动配置中指定固定尺寸:
var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); }) .ConfigureWindows(windows => { windows.WindowDefaults(window => { // 锁定宽高,禁止用户拖拽调整 window.Width = 1290; window.Height = 715; window.MinimumWidth = 1290; window.MaximumWidth = 1290; window.MinimumHeight = 715; window.MaximumHeight = 715; }); }); return builder.Build();
方案二:在运行时动态设置窗口尺寸
如果需要在特定时机调整窗口大小,可通过获取当前窗口实例来设置:
在App.xaml.cs构造函数中设置
public App() { InitializeComponent(); MainPage = new MainPage(); // 获取应用的第一个窗口实例 if (Application.Current?.Windows.FirstOrDefault() is Window targetWindow) { const int fixedHeight = 715; const int fixedWidth = 1290; targetWindow.Width = targetWindow.MinimumWidth = targetWindow.MaximumWidth = fixedWidth; targetWindow.Height = targetWindow.MinimumHeight = targetWindow.MaximumHeight = fixedHeight; } }
在页面的OnAppearing事件中设置
若仅需特定页面生效,可在页面生命周期事件中配置:
protected override void OnAppearing() { base.OnAppearing(); if (Application.Current?.Windows.FirstOrDefault() is Window currentWindow) { const int fixedHeight = 715; const int fixedWidth = 1290; currentWindow.Width = currentWindow.MinimumWidth = currentWindow.MaximumWidth = fixedWidth; currentWindow.Height = currentWindow.MinimumHeight = currentWindow.MaximumHeight = fixedHeight; } }
注意:以上方法仅适用于Windows桌面平台,Android/iOS等移动平台的窗口尺寸由系统控制,无法强制固定。
内容的提问来源于stack exchange,提问作者Bob Gatto
相关产品推荐
相关产品推荐

