Click here to Skip to main content
12,289,457 members (33,516 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# WPF
Is there a way to align text vertically (i.e. centered) inside a wpf button created at run time,I've tried:

Code Snippet


Button btn = new Button();
 
Style style = this.FindResource("ButtonStyle1") as Style; 
btn.Style = style;
 
TextBlock txtTblNme = new TextBlock();
txtTblNme.Text = Convert.ToString(Tbl.SelTblNme(i));
txtTblNme.TextAlignment = TextAlignment.Center;
txtTblNme.VerticalAlignment = VerticalAlignment.Center;
txtTblNme.HorizontalAlignment = HorizontalAlignment.Stretch;
btn.Content = txtTblNme;



but it is not working, & the button doesn't actually force the TextBlock to stretch to the button's width.
Posted 25-Apr-12 12:42pm
Edited 25-Apr-12 15:02pm
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hello

This sample sets the text alignment of MyButton to Right:

MyButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
TextBlock textBlock = new TextBlock()
{
    Text = "Shahin",
    TextAlignment = TextAlignment.Center
};
 
this.MyButton.Content = textBlock;
***
And if you want a XAML code:
<Button  Height="23" HorizontalAlignment="Left" Margin="190,115,0,0" Name="MyButton" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Stretch">
    <TextBlock Text="Shahin" TextAlignment="Center" />
</Button >
  Permalink  
v5
Comments
Doudy_2020 26-Apr-12 9:42am
   
This is not useful , failed to do that , the text does't appear in the center
Shahin Khorshidnia 26-Apr-12 10:50am
   
I updated the solution and changed the Textalignment to Center. By the way the problem solved and you can accept the solution now.
Although it could also help before, just changing ".Right" to ".Center"
VJ Reddy 26-Apr-12 23:37pm
   
+5
Shahin Khorshidnia 26-Apr-12 23:56pm
   
Than you VJ :)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

You have to set following property of button.

btn.VerticalContentAlignment = System.Windows.VerticalAlignment.Center
  Permalink  
Comments
Doudy_2020 26-Apr-12 9:42am
   
This is not useful , failed to do that , the text does't appear in the center

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160518.1 | Last Updated 26 Apr 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100