Xaml文本块设置圆角

27

我试图在xaml中设置TextBlock的圆角,但是没有这样的属性。

<Grid x:Name="grdDis" Grid.Row="1">
        <TextBlock Text="Description" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" Name="txtDescription" Margin="18,10,0,0" Height="128" Width="445"/>
</Grid>

我该如何设置TextBlock的圆角?还想设置TextBlock的背景颜色。

3个回答

68

使用Border控件:

    <Border Margin="5" Padding="5" BorderThickness="1" BorderBrush="Red" Background="AntiqueWhite" CornerRadius="10">
        <TextBlock Text="Lorem ipsum"/>
    </Border>

结果:

输入图像描述


2
当TextBlock具有不同于边框背景颜色的不透明背景颜色时会发生什么?在这种情况下,我认为TextBlock的角落将不会显示为圆形... - Willy
1
@Rodri,抱歉回复晚了。没关系,BorderTextBlock可以正确处理这个问题。已添加截图。 - Dennis

5

为此,请将 Border 元素用作 textBlock 的父元素,如下所示:

 <Border BorderThickness="1" BorderBrush="Black" Background="Green" CornerRadius="5">
    <TextBlock Text="Description"/>
</Border>

你已经得到它了。 :)

1
如对Dennis所说,当TextBlock具有不同的背景颜色(而非透明)且与边框背景颜色不同时,会发生什么情况?在这种情况下,我认为TextBlock的角落将不会呈现出圆形。那么在这种情况下,你如何解决这个问题? - Willy

2

TextBlock没有这样的属性,但是您可以使用Rectangle的RadiusXRadiusY属性,并将Rectangle的宽度和高度绑定到TextBlock的宽度和高度来实现。

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <TextBlock Name="textBlock" Padding="5,0" Text="This is my TextBlock" Height="30" Width="Auto" VerticalAlignment="Top"/>
        <Rectangle RadiusX="5" RadiusY="5" Width="{Binding Width,ElementName=textBlock}" Height="{Binding Height,ElementName=textBlock}" Stroke="White" StrokeThickness="3" VerticalAlignment="Top"/>
</Grid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接