#430 – Setting Width and Height Using Different Units

When you specify the width or height of a control using a value that is a number, the value is interpreted in device independent units (1/96 in).  On a 96 dpi display, device independent units are equivalent to pixels.

<Button Width="80" Height="20" Content="80x20 units" HorizontalAlignment="Center" />

You can also add a suffix to the numeric value, indicating what type of units to use for the dimension.

  • px – device independent units (pixels on 96 dpi).  Same as including no suffix
  • in – inches
  • cm – centimeters
  • pt – points  (1 pt = 1/72 in)
    <StackPanel>
        <Button Width="100" Height="25" Content="100x25 units" HorizontalAlignment="Center" Margin="5"/>
        <Button Width="100px" Height="25px" Content="Also 100x25 units" HorizontalAlignment="Center" Margin="5"/>
        <Button Width="1.5in" Height="0.5in" Content="1-1/2 in x 1/2 in" HorizontalAlignment="Center" Margin="5"/>
        <Button Width="3cm" Height="0.5cm" Content="3 cm x 1/2 cm" HorizontalAlignment="Center" Margin="5"/>
        <Button Width="1in" Height="24pt" Content="1 in x 24 pt" HorizontalAlignment="Center" Margin="5"/>
    </StackPanel>

Advertisement

#203 – Window Size and Location Are Specified in Device Independent Units

The Window class has Left and Top properties that specify the location on the screen of the left and top sides of the window.  It also has Width and Height properties that specify the window’s size.  All of these are expressing in device independent units.

If the current DPI setting is 96 dpi (dots per inch), the WPF units are equivalent to pixels.  I.e. A window specified as 96 units high would appear as 1 inch high.  If the DPI setting is different, the specified WPF units are scaled by dpi/96 to get the resulting pixel value.

In other words:    # pixels = (# WPF Units) * (DPI / 96)

The reason for this is so that WPF applications will appear at roughly the same dimensions on various monitors, regardless of the pixel density.