HomeSearch

WPF Border Example

Use the WPF Border control with BorderBrush. Apply the Stretch property to fill a Window.

Border.

A program interface needs visual clues. The Border control in WPF provides a way to organize an interface into parts. And each part can have a different purpose or use. We use Border to draw colored, visual borders within a Window.

Example.

This example shows some important features of a Border. First, create a WPF application. In the Toolbox, select Border and drag it to your window in the designer. Now, change the Border attributes within the XAML file.

BorderBrush: We can set the BorderBrush to a named color. In this example, I use a red color: Tomato.

BorderThickness: This attribute indicates the number of pixels wide the border itself is.

Alignment: We set the HorizontalAlignment and VerticalAlignment attributes to Stretch. These expand (anchor) the border to the container.

HorizontalAlignment

Also,

I changed the Margin value in the border to equal 10 on each side. The syntax in the XAML here is not optimal. We could instead use the value "10" as the entire margin value. This would expand to "10" on all sides.
Example markup: XAML <Window x:Class="WpfApplication5.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> <Border BorderBrush="Tomato" BorderThickness="3" HorizontalAlignment="Stretch" Margin="10,10,10,10" VerticalAlignment="Stretch"/> </Grid> </Window>

Example 2.

Another element can be nested within a Border element. This means it is possible to use Border to create a section of user interface with sub-controls. And by changing the positioning of these controls, we simplify our program layout.

Here: We nested an "aqua" border within our "tomato" border. We use the simplified margin syntax. We set the thickness to 3.

Example markup 2: XAML <Window x:Class="WpfApplication5.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> <Border BorderBrush="Tomato" BorderThickness="3" HorizontalAlignment="Stretch" Margin="10" VerticalAlignment="Stretch"> <Border BorderBrush="Aqua" BorderThickness="3" Margin="10"/> </Border> </Grid> </Window>

Summary.

Borders in WPF provide another way to create visual distinction within your program. We can add colors to them, adjust their thickness, and change their alignments—even stretch them. We can nest other controls within a Border.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.