如何获取WPF窗口以自动调整内容大小,仅此而已 [英] How to get WPF Window to autosize to content and no more

查看:84
本文介绍了如何获取WPF窗口以自动调整内容大小,仅此而已的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对话框,其中包含2个TextBlock,一个进度栏和一个取消按钮.

I have a dialog containing 2 TextBlocks, a Progress Bar and a cancel Button.

这是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的高度分配任何内容时,似乎采用的高度要大于内容的高度.

I would like the Window not to have a fixed height but auto adjust its height based on the size of its children and no more, but can’t see a way to do this. At the moment when I don’t assign anything to the Window’s height, it seems to adopt a height that is much bigger that the content.

不确定为什么,或从何处获取高度值?如果将Windows Height设置为"Auto",我会得到相同的结果. RowDefinitions的所有高度都设置为自动",我的意思是将行高度设置为行子高度".

Not sure why, or where it gets height value from? If I set Windows Height = "Auto" I get the same thing. All the heights for the RowDefinitions are set to "Auto", which I take to mean ‘set row height to be row child height’.

推荐答案

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

You need to use SizeToContent property, check the 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">

这篇关于如何获取WPF窗口以自动调整内容大小,仅此而已的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆