Search code examples
wpfxamlheightwidth

Trying to set width and height of the window to auto


I am trying to make the width and height of the window to be auto which means it will have the width and height of all its children control combined:

My Code:

<Window x:Class="Read_360.ToastPopup"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ToastPopup" Width="Auto" Height="68">
    <Window.Resources>
        <ControlTemplate x:Key="MyErrorMessage"
                         TargetType="{x:Type Label}">
            <StackPanel Orientation="Horizontal"
                        Name="ErrorMessage" Width="Auto" Height="Auto">
                <Border CornerRadius="4" Width="Auto"
                        BorderThickness="0"
                        VerticalAlignment="Center"
                        Margin="4,0"
                        Background="#FF404040"
                        BorderBrush="Transparent">
                    <Label Foreground="White"
                           VerticalAlignment="Center"
                           Padding="4,2"
                           Margin="4"
                           FontWeight="Bold" FontSize="15"
                           Name="Part1" Width="Auto" Height="Auto"
                           Visibility="Visible" HorizontalAlignment="Center" Content="{Binding Message}" />
                </Border>
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <Label Template="{StaticResource MyErrorMessage}" Name="Label1" Width="Auto" Height="Auto"></Label>
    </StackPanel>
</Window>

I need the width and height to be the same as the Label which is inside the ControlTemplate.


Solution

  • You should be able to set the SizeToContent property on your window to WidthAndHeight to achieve this.