如何在运行时将文本在WPF按钮内居中对齐? [英] How to center align text inside a WPF button at runtime?

查看:181
本文介绍了如何在运行时将文本在WPF按钮内居中对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在运行时创建的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;





但它不起作用,&按钮实际上并没有强制TextBlock拉伸到按钮的宽度.





but it is not working, & the button doesn''t actually force the TextBlock to stretch to the button''s width.

推荐答案

Hello

此示例将MyButton的文本对齐方式设置为Right:

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;


***
如果您需要 XAML 代码:


***
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 >


您必须设置button的following属性.

btn.VerticalContentAlignment = System.Windows.VerticalAlignment.Center
You have to set following property of button.

btn.VerticalContentAlignment = System.Windows.VerticalAlignment.Center


这篇关于如何在运行时将文本在WPF按钮内居中对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆