如何让WPF窗口自适应内容且不超出

47

我有一个对话框,其中包含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>
我希望窗口高度不是固定的,而是根据其子元素的大小自动调整高度,但我无法找到一种方法来实现这一点。目前,当我没有为窗口高度分配任何值时,它似乎采用比内容更大的高度。
我不确定为什么会这样,或者它从哪里获取高度值?如果我将窗口高度设置为“自动”,我得到相同的结果。所有行定义的高度都设置为“自动”,我理解为“将行高设置为行中子元素的高度”。

12
Window SizeToContent="Height" 是什么意思? - ASh
3
你应该考虑接受这个答案。 - StayOnTarget
1个回答

100
您需要使用 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">

我很高兴SizeToContent起作用了,但我想知道为什么width="Auto"失败得如此严重。我的窗口的宽度几乎是内容的两倍。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接