WinUI 3中如何根据屏幕缩放动态调整窗口大小?
WinUI 3 窗口适配动态DPI缩放的解决方案
区分逻辑像素与物理像素
WinUI 3 中XAML布局使用逻辑像素,而AppWindow.MoveAndResize接收的是物理像素值。你之前固定设置的1200×665如果是逻辑像素,在125%缩放(DPI因子1.25)下对应物理像素1500×832,但切换到150%缩放时,固定物理像素会导致逻辑窗口被压缩,控件因超出可视区域消失。获取当前显示器的DPI缩放因子
通过DisplayInformation类获取当前窗口所在显示器的缩放比例:
var displayInfo = DisplayInformation.GetForCurrentView(); double scaleFactor = displayInfo.RawPixelsPerViewPixel;
RawPixelsPerViewPixel直接对应缩放比例(125%为1.25,150%为1.5)。
- 动态计算并调整窗口大小
先定义你期望的逻辑窗口大小(比如原本适配125%的1200×665),再根据当前缩放因子转换为物理像素后调整窗口:
// 理想逻辑窗口尺寸 double logicalWidth = 1200; double logicalHeight = 665; var displayInfo = DisplayInformation.GetForCurrentView(); double scale = displayInfo.RawPixelsPerViewPixel; // 转换为物理像素并取整 int physicalWidth = (int)Math.Round(logicalWidth * scale); int physicalHeight = (int)Math.Round(logicalHeight * scale); // 调整窗口位置与大小 this.AppWindow.MoveAndResize(new Windows.Graphics.RectInt32( this.AppWindow.Position.X, this.AppWindow.Position.Y, physicalWidth, physicalHeight ));
- 监听DPI变化实现自动适配
注册DpiChanged事件,在用户切换缩放比例时自动调整窗口:
public WelcomeScreen() { this.InitializeComponent(); // 初始化时适配一次 AdjustWindowSizeForDpi(); // 监听DPI变化 DisplayInformation.GetForCurrentView().DpiChanged += OnDpiChanged; } private void OnDpiChanged(DisplayInformation sender, object args) { AdjustWindowSizeForDpi(); } private void AdjustWindowSizeForDpi() { double logicalWidth = 1200; double logicalHeight = 665; double scale = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; int physicalWidth = (int)Math.Round(logicalWidth * scale); int physicalHeight = (int)Math.Round(logicalHeight * scale); this.AppWindow.MoveAndResize(new Windows.Graphics.RectInt32( this.AppWindow.Position.X, this.AppWindow.Position.Y, physicalWidth, physicalHeight )); }
- 确保控件布局自适应
控件消失可能还和固定尺寸布局有关,检查XAML:- 避免给控件设置固定
Width/Height,改用HorizontalAlignment="Stretch"/VerticalAlignment="Stretch"填充可用空间。 - 优先用
Grid、StackPanel等自适应容器,少用绝对定位的Canvas。 - 需固定比例的控件可套入
Viewbox,或设置MaxWidth/MaxHeight限制最大尺寸。
- 避免给控件设置固定
内容的提问来源于stack exchange,提问作者Ming
相关产品推荐
相关产品推荐

