Dealing with Percentage Size in WPF


In HTML, percentage (%) symbol is used to define uniform layout that keeps the same width and height ratio when a Web page is resized. We did not have this feature in Windows Forms. However, WPF support this feature in a different manner by using an asterisk (*) suffix with a double number. Unlike percentage, an asterisk does not have maximum limit of 100. An asterisk uses current width or height of an element and divides by the value associated with the asterisk and when a Window or Page is resized, the actual size of the element is calculated at runtime.

Here is an example. Figure 1 is a Window with a Grid panel and three Rectangle elements.

PerImg1.gif

Figure 1

You can create this UI by simply placing 3 rectangles on a Grid element and moving them where you want.  The XAML code looks like Listing 1.

<Grid>      

    <Rectangle Name="rectangle1" Stroke="Black" Fill="Orange" Margin="55,0,112,80" />

    <Rectangle Fill="Green" Margin="0,80,0,0" Name="rectangle2" Stroke="Black"

               HorizontalAlignment="Right" Width="113" />

    <Rectangle Fill="Purple" Margin="0,80,0,0" Name="rectangle3" Stroke="Black"

               HorizontalAlignment="Left" Width="54" />

</Grid>

Listing 1

Now when we resize the Window, we want the size of the rectangles have same ratio as new size of the Window. We can achieve this using an asterisk with the size.

However, all elements in XAML do not support asterisk feature. We place columns and rows in a Grid element and fix their width and height with the asterisk.

The new code is listed in Listing 2.

<Window x:Class="PercentageInWPF.Window1"

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

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

    Title="Window1" Height="200" Width="300">

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="139*" />

            <RowDefinition Height="150*" />

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="101*" />

            <ColumnDefinition Width="208*" />

            <ColumnDefinition Width="169*" />

        </Grid.ColumnDefinitions>

        <Rectangle Grid.Column="1" Name="rectangle1" Stroke="Black" Fill="Orange" />

        <Rectangle Fill="Green" Name="rectangle2" Stroke="Black" Grid.Column="2" Grid.Row="1" />

        <Rectangle Fill="Purple" Name="rectangle3" Stroke="Black" Grid.Row="1" />     

    </Grid>

</Window>

Listing 2

Now if you resize the Window, the size of rectangles will be changed in proportional to the size of the Window.

PerImg2.gif

Figure 2

Download the attached source code for more details.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.