WPF Layout: Content Alignments

Proper layout and positioning are a vital part of interactive, high-performance and user-friendly Windows applications. In a series of articles, I will discuss the layout process in WPF. The series starts with an understanding of the WPF layout process. The next part of this series will cover the basics of layout and positioning such as size, margin, padding and alignment of elements. Later in this series, I will cover various panels and related parent controls available in WPF.

Table of Contents

Introduction

In the previous article, WPF Layout: Horizontal and Vertical Alignment, we saw vertical and horizontal alignment of elements. However the preceding topic did not cover the alignment of contents of elements. This article focuses on the content alignment of elements.

Content Alignment

The content of content controls in WPF is dealt using various properties. These two properties are HorizontalContentAlignment and VerticalContentAlignment. These properties are defined in the System.Windows.Controls.Control class that is the parent class of all controls in WPF.

Similar to the HorizontalAlignment and VerticalAlignment, both properties are of type HorizontalAlignment and VerticalAlignment enumerations respectively.

If you create a UI with a Button and a TextBox control, the UI looks as in Figure 1 where the default vertical and horizontal alignment of content of a Button is center. The default vertical and horizontal alignment of content of a TextBox is left and top.


                                           Figure 1

Now what if you want to place contents of a Button and TextBox on different positions? Let's say, you want to set the contents of the Button and TextBox to bottom and right. This comes handy when the size of elements is larger than the size of contents.

The code listed in Listing 1 sets VerticalContentAlignment and HorizontalContentAlignment properties to bottom and right.

  1. <Grid Name="StackPanel1" Background="LightGray" >  
  2.    <Button Name="Button1" Background="LightBlue" Height="45"  
  3.       Content="Click Me!" Margin="23,12,159,0" VerticalAlignment="Top"  
  4.       FontSize="16" FontWeight="Bold"  
  5.       VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />  
  6.    <TextBox Height="50" Margin="26,72,74,0" Name="textBox1" VerticalAlignment="Top"  
  7.       Text="I am a TextBox" FontSize="16"  
  8.       VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />  
  9. </Grid>  

Listing 1

Listing 1 generates output that looks as in Figure 2. As you can see in Figure 2, the contents of the Button and TextBox are aligned bottom and right.


                                           Figure 2

Summary

In this article, I discussed the content alignment of WPF elements. In the next article of this series, I will discuss how to deal with a % size of WPF elements.