仅将窗口设置为所需大小

问题描述 投票:0回答:1

在WinUI 3中,如何使窗口只达到需要的大小?请注意,它应该调整其大小,以防应用程序运行时内容变大。

(反面)示例:

<?xml version="1.0" encoding="utf-8"?>
<Window
    x:Class="SampleApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SampleApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
    </StackPanel>
</Window>

获取此窗口大小,注意窗口如何比内容(按钮)大得多:

c# xaml window winui-3
1个回答
0
投票

根据此讨论: https://github.com/microsoft/microsoft-ui-xaml/discussions/9404

SizeChanged
事件处理程序添加到窗口的根元素。事件处理程序应该大致如下所示:

private void OnRootSizeChanged(object sender, SizeChangedEventArgs e)
{
    var elm = (FrameworkElement)sender;
    elm.SizeChanged -= OnRootSizeChanged;

    var height = (int)Math.Ceiling(elm.DesiredSize.Height);
    var width = (int)Math.Ceiling(elm.DesiredSize.Width);

    AppWindow.ResizeClient(new(width, height));
    Activate();
}
© www.soinside.com 2019 - 2024. All rights reserved.