Google News
logo
WPF - Interview Questions
Explain Content Alignment in WPF?
 
You can change the alignment of text in text boxes and buttons using content alignment. The content of content controls can be controlled by a number of properties in WPF. Two of these properties are:  
 
* HorizontalContentAlignment
* VerticalContentAlignment

System.Windows.Controls.Control, the parent class for all WPF controls, defines these properties. 
 
Example : 
Suppose you want to create a UI (User Interface) with a Button and TextBox. The default vertical/horizontal alignment of a button's content is center, while the default vertical/horizontal alignment of a TextBox is top and left, as shown below. 

Content Alignment
But what if you want TextBoxes and Button contents positioned differently? Let's say you want to place the content of the Button and TextBox right and bottom, respectively. 
 
VerticalContentAlignment and HorizontalContentAlignment properties are set to bottom and right, respectively, in the following code. 
<Grid Name="StackPanel1" Background="LightGray" >   
  <Button Name="Button1" Background="LightBlue" Height="45"   
     Content="Click Me!" Margin="23,12,159,0" VerticalAlignment="Top"   
     FontSize="16" FontWeight="Bold"   
     VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />   
  <TextBox Height="50" Margin="26,72,74,0" Name="textBox1" VerticalAlignment="Top"   
     Text="I am a TextBox" FontSize="16"   
     VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" />   
</Grid>
It produces output similar to that shown below. You can see that the content in the TextBox and Button are aligned to the right and bottom, respectively. 

Content Alignment
Advertisement