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

C# 如何让WPF窗口自动调整为内容大小,而不是更多,c#,wpf,xaml,layout,wpf-controls,C#,Wpf,Xaml,Layout,Wpf Controls,我有一个包含两个文本块、一个进度条和一个取消按钮的对话框 以下是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.microso

我有一个包含两个文本块、一个进度条和一个取消按钮的对话框

以下是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>

这是一条很长的绳子
我希望窗口不是固定高度,而是根据其子窗口的大小自动调整其高度,但看不到实现此目的的方法。当我没有为窗口的高度指定任何内容时,它似乎采用了比内容大得多的高度


不知道为什么,或者从哪里获取高度值?如果我设置Windows Height=“Auto”,我会得到同样的结果。行定义的所有高度都设置为“自动”,我认为这意味着“将行高度设置为行子级高度”。

您需要使用
SizeToContent
属性,请检查

例如:



Window怎么样
SizeToContent=“Height”
?@ASh,非常感谢!现在工作!你应该考虑接受这个答案。