4

I'm trying to create a quadratic window with a size of 300x300. But the window's size doesn't seem to reflect what I wrote into my XAML. For example, I created a completely new window and set

Height="300" Width="300"

I didn't change or add anything else. The window shows correctly as 300x300 in the Designer. But when I run the program I get a window that's 284x291. Why? If I set it to 309x316 the window becomes 300x300.

This is really a big problem, since controls are actually going out of bounds now. I designed this window:

mainwindowdesigner

<Window ...
    Title="MainWindow" Height="150" Width="300">
<Grid>
    <StackPanel Margin="10">
        <TextBox Margin="0,0,0,10" Text="Textbox"/>
        <TextBox Margin="0,0,0,10" Text="Textbox"/>
        <TextBox Margin="0,0,0,10" Text="Textbox"/>
        <Button Content="Test"/>
    </StackPanel>
</Grid>

But the actual window looks like this:

windowactual

Am I supposed to add random pixel values to the height until it fits in the window? I don't really understand why the size is different and how I'm supposed to deal with it.

Zelos
  • 107
  • 6
  • 1
    You shouldn't really be setting height/width in pixels. It will look bad on high DPI screens if you do that. What happens if you don't specify H/W? Do all your controls then fit? – Neil May 17 '21 at 13:38
  • 2
    @Neil I'm a bit confused why those are set in the XAML by default when I create a new window then. If I don't specify anything the window is 1424x758. I really wonder where exactly this number is coming from. – Zelos May 17 '21 at 15:29

1 Answers1

5

I get a window that's 284x291. Why?

The provided size (300x300) is only a suggested value.

Am I supposed to add random pixel?

No, you are supposed to think your application as pixel independent as much as possible.

In your case, anyway, you may want do make a pop-up like window, not resizable and with a size that fit the content.

<Window x:Class="WpfApp1.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"
        mc:Ignorable="d"
        Title="MainWindow"
        ResizeMode="NoResize"
        SizeToContent="Height"
        Width="300">
    <Grid>
        <StackPanel Margin="10">
            <TextBox Margin="0,0,0,10" Text="Textbox"/>
            <TextBox Margin="0,0,0,10" Text="Textbox"/>
            <TextBox Margin="0,0,0,10" Text="Textbox"/>
            <Button Content="Test"/>
        </StackPanel>
    </Grid>
</Window>
Orace
  • 7,822
  • 30
  • 45
  • 1
    Thank you, I think I get it now. I was just confused because newly created windows have absolute values set for these. I'm coming from Winforms, so I'm used to just dragging the window as big as I need it. – Zelos May 17 '21 at 15:30