如何让WPF窗口自动调整内容大小,而不是更多

本文关键字:WPF 窗口 调整 | 更新日期: 2023-09-27 18:13:34

我有一个包含2个textblock,一个进度条和一个取消按钮的对话框。

这里是XAML:
<Window x:Class="WpfApplication4.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:WpfApplication4"
    mc:Ignorable="d"
    Title="MainWindow" Height="Auto" Width="200">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="txtFirst" Grid.Row="0"  Margin="5" TextWrapping="Wrap">This is a really really really really long string that wraps</TextBlock>
    <TextBlock x:Name="txtSecond" Grid.Row="1"  Margin="5" Text="A Shorter string" TextWrapping="Wrap" MaxWidth="200"/>
    <ProgressBar x:Name="prgProgress" Grid.Row="2" Margin="5" Height="20" />
    <Button x:Name="btnCancel" Grid.Row="3" Margin="5" Height="25" Width="50"/>
</Grid>
</Window>

我希望窗口没有固定的高度,而是根据其子的大小自动调整其高度,没有更多,但看不到这样做的方法。当我没有给窗口的高度分配任何东西时,它似乎采用了一个比内容大得多的高度。

不知道为什么,或者它从哪里得到高度值?如果我设置window Height = " Auto "我也会得到相同的结果。rowdefinition的所有高度都设置为"Auto",我认为这意味着"将行高度设置为行子高度"。

如何让WPF窗口自动调整内容大小,而不是更多

您需要使用SizeToContent属性,检查msdn链接。

的例子:

<Window 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"
        …
        SizeToContent="WidthAndHeight">