窗口未调整为内容的大小



>我有一个窗口:

<Window x:Class="HarryPotter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:HarryPotter"
        mc:Ignorable="d"
        Title="Harry Potter" SizeToContent="WidthAndHeight" Background="Black" WindowStartupLocation="CenterScreen"
        >
    <Viewbox Stretch="Uniform">
        <Canvas Height="640" Width="480" Background="DodgerBlue">
        </Canvas>
    </Viewbox>
</Window>

在设计器中,ViewBox 的宽度 = 480,高度 = 640。因此,窗口的宽度和高度分别为 488 和 671。这正是我想要的。

我希望 ViewBox 在启动时的大小与 Canvas 相同,并且窗口的大小与 ViewBox 的大小相同。然后我希望窗口可以自由调整大小。然而,事实并非如此。当窗口打开时,它的高度就是我的显示器的高度。

我该如何解决这个问题?

您正在使用ViewBox通过均匀拉伸内容来使其适应可用空间。但是,由于您没有为可用空间(SizeToContent = "WidthAndHeight")定义高度或宽度,因此它会占用所有空间,以便可以拉伸画布。

要进行实验,您可以设置Height="50"并查看窗口占用了所有水平空间。

为了防止它,您有几种选择:

  • ViewBox属性设置为 None Stretch 而不是 Uniform
  • Window设置预定义的WidthHeight
  • 设置MaxHeightMaxWidth属性 ViewBox

最新更新