以下是一个名为 'CenteredTextBlock' 的样式,它设置了 TextBlock 的字体大小为 16,并将其水平和垂直居中:

<Style x:Key='CenteredTextBlock' TargetType='TextBlock'>
    <Setter Property='FontSize' Value='16'/>
    <Setter Property='VerticalAlignment' Value='Center'/>
    <Setter Property='HorizontalAlignment' Value='Center'/>
</Style>

可以在需要使用此样式的 TextBlock 上应用它:

<TextBlock Style='{StaticResource CenteredTextBlock}' Text='Hello, world!'/>

如果需要在此基础上增加垂直和水平内容居中,可以定义一个新的样式,继承自 'CenteredTextBlock',然后在其中增加 'VerticalContentAlignment' 和 'HorizontalContentAlignment' 属性的设置:

<Style x:Key='CenteredAndAlignedTextBlock' TargetType='TextBlock' BasedOn='{StaticResource CenteredTextBlock}'>
    <Setter Property='VerticalContentAlignment' Value='Center'/>
    <Setter Property='HorizontalContentAlignment' Value='Center'/>
</Style>

同样可以在需要使用此样式的 TextBlock 上应用它:

<TextBlock Style='{StaticResource CenteredAndAlignedTextBlock}' Text='Hello, world!'/>
WPF 样式:水平垂直居中 TextBlock

原文地址: https://www.cveoy.top/t/topic/nwya 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录