Click here to Skip to main content
Rate this: bad
good
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 at 26-Apr-12 9:42am
   
This is not useful , failed to do that , the text does't appear in the center
Shahin Khorshidnia at 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 at 26-Apr-12 23:37pm
   
+5
Shahin Khorshidnia at 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 at 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
0 Dnyaneshwar@Pune 1,310
1 Sergey Alexandrovich Kryukov 726
2 Tadit Dash 345
3 OriginalGriff 313
4 Manas Bhardwaj 215
0 Sergey Alexandrovich Kryukov 11,700
1 OriginalGriff 6,980
2 Peter Leow 4,915
3 Abhinav S 3,838
4 Maciej Los 3,575


Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 26 Apr 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid