Click here to Skip to main content
11,718,589 members (73,595 online)
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 Sergey Alexandrovich Kryukov 651
1 OriginalGriff 210
2 F-ES Sitecore 185
3 Jochen Arndt 160
4 Maciej Los 130
0 OriginalGriff 535
1 Maciej Los 529
2 Richard MacCutchan 440
3 CHill60 415
4 F-ES Sitecore 415


Advertise | Privacy | Mobile
Web04 | 2.8.150901.1 | Last Updated 26 Apr 2012
Copyright © CodeProject, 1999-2015
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