如何为 TextBlock 中的文本创建边框?

How to create a border for the text in the TextBlock?

我想为 TextBlock 中的文本创建边框。

我尝试使用投影,但遇到了问题。问题出在 DropShadowPanel。我已报告问题

所以我需要一个替代方法来为 TextBlock 中的文本创建边框。

作为参考,我希望文本看起来像这样:

<Grid HorizontalAlignment="Left">
    <TextBlock Text="TextBlock" TextWrapping="Wrap" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" OpacityMask="Black" />
    <Border BorderBrush="#FF0B232F" BorderThickness="2" />
</Grid>

此外,请在此处查看此 link,它拥有您需要的一切,甚至更多:

https://msdn.microsoft.com/en-us/library/ms745816.aspx

由于您在使用 DropShadowPanel 时遇到问题,我猜您想要文本的阴影,而不是边框​​。

如果是这种情况,您可以执行以下操作:

<TextBlock Text="My text" Foreground="Black" RenderTransformOrigin="0.5,0.5"  >
    <TextBlock.RenderTransform>
        <CompositeTransform TranslateX="1" TranslateY="1"/>
    </TextBlock.RenderTransform>
</TextBlock>
<TextBlock Text="My text"  Foreground="White" />

这将产生阴影效果。

编辑

我想我已经得到了你想要的。 XAML.

中仍然需要两个 TextBlock
<Grid x:Name="grid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <!--TextBlock that will receive the shadow-->
    <TextBlock FontSize="46" Text="My text"  Foreground="White" x:Name="shadowTextBlock" />
    <!--Let this TextBlock foreground black just for design time-->
    <TextBlock FontSize="46" Text="My text"  Foreground="Black" x:Name="foregroundTextBlock"/>
</Grid>

然后您需要在 page_loaded 处输入以下代码:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    // Set the right color to the foreground text
    this.foregroundTextBlock.Foreground = this.shadowTextBlock.Foreground;

    var compositor = ElementCompositionPreview.GetElementVisual(this.grid).Compositor;
    var spriteVisual = compositor.CreateSpriteVisual();
    spriteVisual.Size = this.grid.RenderSize.ToVector2();

    var dropShadow = compositor.CreateDropShadow();
    dropShadow.Mask = this.shadowTextBlock.GetAlphaMask();
    dropShadow.Color = Colors.Black;
    dropShadow.Offset = new Vector3(0, 0, -50);
    spriteVisual.Shadow = dropShadow;

    ElementCompositionPreview.SetElementChildVisual(this.shadowTextBlock, spriteVisual);
}

结果真的很像你的例子:

您甚至不需要网格来放入它们。只需将 TextBlock 放入 Border 控件中即可:

<Border BorderBrush="Black" BorderThickness="2">
    <TextBlock Text="TextBlock" FontSize="12" Foreground="Black" />
</Border>

这应该可以解决问题。

注意:Windows 需要周年更新 (10.0.14393.0) 才能正确支持此效果。

UWPCommunityToolkit 将通过更新修复此 issue for DropShadowPanel,但我们可以通过为 DropShadowPanel 添加 'HorizontalAlignment="Left"' 来手动修复此问题。

使用Microsoft.Toolkit.Uwp.UI.Controls

<controls:DropShadowPanel BlurRadius="3" ShadowOpacity="1" OffsetX="0" OffsetY="0" Color="Black">
    <TextBlock FontSize="42" Text="Vijay Nirmal" Foreground="White"/>
</controls:DropShadowPanel>