【问题标题】:How to get WPF Window to autosize to content and no more如何让 WPF 窗口自动调整为内容大小
【发布时间】:2017-02-27 10:11:14
【问题描述】:

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

这是 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 不具有固定高度,而是根据其子项的大小自动调整其高度,但没有办法做到这一点。在我没有为 Window 的高度分配任何东西的那一刻,它似乎采用了比内容大得多的高度。

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

【问题讨论】:

  • Window SizeToContent="Height"怎么样?
  • @ASh,非常感谢!现在可以使用了!
  • 你应该考虑接受答案

标签: c# wpf xaml layout wpf-controls


【解决方案1】:

你需要使用SizeToContent属性,检查msdn link

例子:

<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">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多