Home > Software design >  Why is there extra space on WPF?
Why is there extra space on WPF?

Time:05-27

this is in XAML Designer

Expected:

enter image description here

Actual:

enter image description here

This is my window's XAML:

<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"
    xmlns:local="clr-namespace:WpfApp2"
    xmlns:Wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf" x:Class="WpfApp2.MainWindow"
    mc:Ignorable="d"
    ResizeMode="NoResize"
    Title="MainWindow" SizeToContent="WidthAndHeight" AllowsTransparency="True" WindowStyle="None" Loaded="Window_Loaded">
<StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <StackPanel.Resources>
            <Style TargetType="Button">
                <Setter Property="Margin" Value="5, 0, 5, 0"></Setter>
                <Setter Property="Height" Value="30"></Setter>
            </Style>
        </StackPanel.Resources>
        <Button>测试</Button>
        <Button>测试</Button>
        <Button>测试</Button>
    </StackPanel>
    <Canvas Height="2" Background="Red" />
</StackPanel>

There is extra space around the window.

I found that as long as the height is less than 40, there will be extra space.But I didn't set minHeight.

this is my app.xaml:

<Application x:Class="WpfApp2.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:WpfApp2"
         StartupUri="MainWindow.xaml">
<Application.Resources>
     
</Application.Resources>

my environmental information:

Windows 11

Visual Studio 2022

.net framework 4.8

CodePudding user response:

In WPF SizeToContent does not work very well with WindowStyle=None. It seems the renderer is still taking a non-existant border into account when initially drawing the Window.

A simple hack to overcome this: set Height="1" on the Window to force its initial size to something smaller than the eventual size. Then when the content is rendered, SizeToContent="WidthAndHeight" will cause the window to resize itself to the correct size.

  • Related