Click here to Skip to main content
15,902,635 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Is there a way to align text vertically (i.e. centered) inside a wpf button created at run time,I've tried:

Code Snippet


C#
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
Updated 25-Apr-12 15:02pm
v2

Hello

This sample sets the text alignment of MyButton to Right:

C#
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:
HTML
<Button  Height="23" HorizontalAlignment="Left" Margin="190,115,0,0" Name="MyButton" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Stretch">
    <TextBlock Text="Shahin" TextAlignment="Center" />
</Button >
 
Share this answer
 
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 :)
You have to set following property of button.

btn.VerticalContentAlignment = System.Windows.VerticalAlignment.Center
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900