Search code examples
wpfxaml

WPF units on window and canvas are different. What is window size unit?


When I create a WPF project and run the code below I get the window below. I am confused, as both ellips diameter and window width/height are "200", but ellipse does not fit in window.

Also, I am not posting an image, but I tried to set the height and width of the window to 96 in a previous experiment, and the height was less than width. The aspect ratio kinda looked like the aspect ratio of my display.

I read that in WPF each unit is 1/96 inches. I assume this is true for ellipse in the canvas. Then, what about the window size? What unit does it use?

image:

Simple WPF application window image.

code:

<Window x:Class="clock2.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:clock2"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200">
    <Grid>
        <Canvas ClipToBounds="True">
            <Ellipse Canvas.Left="0.0" Canvas.Top="0.0" Width="200.0" Height="200.0" Fill="lightgray" />

        </Canvas>

    </Grid>
</Window>

Solution

  • The Width and Height of the Window includes the dimensions of the border and title bar.

    Set the size of the Grid instead, and set SizeToContent="WidthAndHeight" on the Window:

    <Window ... SizeToContent="WidthAndHeight">
        <Grid Height="200" Width="200">
            <Canvas ClipToBounds="True">
                <Ellipse Canvas.Left="0.0" Canvas.Top="0.0"
                         Width="200.0" Height="200.0" Fill="LightGray" />
            </Canvas>
        </Grid>
    </Window>