Adjusting Control Size in WPF


While working with WPF applications first thing we have to focus is controlling size and position of WPF controls. In WPF setting the controls size and position is called Layout. Layout is nothing but interaction between Parent elements and its child elements to adjust its size & position in WPF window. Parent element which contains multiple child elements is called Panel and it derives from System.Windows.Controls.Panel class. All WPF controls including parent and child elements derives from System.Windows.UIElement. In this article we discuss about how to set the Size for WPF controls.

 

WPF controls has simple Height and Width property to set its height and width which takes double type value. By default in WPF any control takes size as small as possible. We can mention MinHeight and MinWidth properties to control, so that it takes Height and Width unless its content forces it to grow. WPF control width and height can be limited by MaxWidth and MaxHeight properties. The default value of MinHeight and MinWidth are 0; the default value of MaxHeight and MaxWidth are Double.PositiveInfinity.

 

As shown below we can set the Width, Height, MinWidth, MinHeight, MaxWidth & MaxHeight properties.

 

<Window x:Class="WPFSizePosition.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <Label Width="100" Height="100" MinHeight="50" MinWidth="50" MaxHeight="500" MaxWidth="500">This is the Label control</Label>

    </Grid>

</Window>

 

As shown above Label control takes minimum of 50px for width and height; maximum of 500px for width and height.

 

Other than these properties we have some more read-only properties, those are DesiredSize, RenderSize, ActualHeight, and ActualWidth off the WPF controls. DesiredSize provides actual desired size of the element, RenderSize represents actual size particular element takes. ActualHeight and ActualWidth provides the same as RenderSize.Height and RenderSize.Width.

 

Margin and Padding properties of WPF control also will affect the size of the controls. Margin affects the space outside of the control, Padding affects the space within the control. As shown below we can mention Margin and Padding for the control.

 

<Window x:Class="WPFSizePosition.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <Label Margin="10,10,20,30" Padding="5,4,7,8">This is the Label control</Label>

    </Grid>

</Window>

 

Margin and Padding takes values as Left,Top,Right,Bottom positions.

 

 

Add comment