lost9123193
lost9123193

Reputation: 11040

Text Block Not Aligning

I have the following Textblock and I can't seem to get the text to align:

TextBlock headerBlock;
Canvas headerContainer;

public setLayout()
{
   headerContainer= new Canvas();
   headerContainer.Background = new Brushes.Black;

   headerBlock= new TextBlock();
   headerBlock.FontSize = 10;
   headerBlock.Text = "This must be centered";
   headerBlock.TextAlignment = System.Windows.TextAlignment.Center;
   headerBlock.Foreground = Brushes.White;
   headerBlock.Padding = new System.Windows.Thickness(20);


   headerContainer.Children.Add(headerBlock);

}

For some reason, the TextAlignment does not align the text. Is there something else I can add to force the headerBlock text to align center?

Upvotes: 0

Views: 531

Answers (2)

P.Manthe
P.Manthe

Reputation: 960

This behavior is due to the Canvas.

=> Canvas are made to organize elements according to pixel positions. Replace your Canvas by a Grid and it will work.

You will also have to write what zambonee suggested:

TextAlignment will align text inside the control. HorizontalAlignment and VerticalAlignment will align the control inside its container.

=> Play with both to obtain what you need.

Upvotes: 2

zambonee
zambonee

Reputation: 1647

The TextBlock is not expanding to fill its parent, and is probably jammed into its parent's top-left corner. Try this

headerBlock.HorizontalAlignment = HorizontalAlignment.Center; //or Stretch with TextAlignment = Center
headerBlock.VerticalAlignment = VerticalAlignment.Center; //or Stretch

Upvotes: 0

Related Questions