How to get a WPF window to automatically configure content and no more

I have a dialog containing 2 TextBlocks, a progress bar and a cancel button.

Here is the 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>

I would like the Window to not have a fixed height, but automatically adjust its height depending on the size of its children and nothing more, but I can’t find a way to do this. At that moment, when I do not assign anything to the height of Windows, it seems that it takes on a height that is much larger than the content. Not sure why, or where it gets the height value? If I set Windows Height = "Auto", I get the same. All heights for RowDefinitions are set to "Auto", which I mean "set the height of the row so that it is the height of the child.

Thanks so much for any help.

+4

Source: https://habr.com/ru/post/1658063/


All Articles