WPF向TextBlock添加边框

88

如何给文本块(TextBlock)添加边框?我需要在下面的代码setter属性中添加它:

<Style x:Key="notCalled" TargetType="{x:Type TextBlock}">
    <Setter Property="Margin" Value="2,2,2,2" />
    <Setter Property="Background" Value="Transparent" />
</Style>

2
请使用文本框。 - Jim Balter
3个回答

164

你需要将 TextBlock 放在一个 Border 中。例如:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

当然,你也可以通过样式来设置这些属性(BorderThicknessBorderBrush):

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

36

TextBlock不是从Control继承而来,因此它没有通常与Control相关的属性。如果您想在样式中添加边框,最好将TextBlock替换为Label。

有关TextBlock和其他控件之间差异的更多信息,请参见此链接


那个链接提供了我不知道的很棒的信息。我更喜欢这个解决方案,因为@Heinzi的解决方案在我的应用中不起作用。尽管尝试了那个解决方案,但边框仍然没有显示。 - AdvApp
我因此一直在苦苦思索。我也想到用Label替换TextBlock,但是你猜怎么着:Label不支持绑定中的格式字符串。在XAML中,您可以添加格式字符串到标签绑定而不会导致语法错误,并且该程序编译和运行时没有异常。然而,标签只是不关心其绑定中的格式字符串。因此,我不得不采取将TextBlock包装在Border中的方法。真是一团糟... - Binarus

0
<Label Name="Lbl_IP2"  Style="{StaticResource LabelWithBorder}" Content="3"/>

<Style TargetType="Label" x:Key="LabelWithBorder">
  <Setter Property="Padding" Value="10,5,10,5"/>
  <Setter Property="Background" Value="#202020"/>
  <Setter Property="Foreground" Value="#fff"/>
  <Setter Property="Width" Value="auto"/>
  <Setter Property="FontFamily" Value="Arial"/>
  <Setter Property="FontSize" Value="20"/>
  <Setter Property="HorizontalAlignment" Value="Center"/>
  <Setter Property="FlowDirection" Value="LeftToRight"/>

  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Label}">
        <Border SnapsToDevicePixels="true" Background="#000" BorderBrush="AliceBlue" BorderThickness="1" Padding="5">
          <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" RecognizesAccessKey="True">
            <ContentPresenter.Effect>
              <DropShadowEffect BlurRadius="15" Direction="-90" RenderingBias="Quality" ShadowDepth="2" Opacity="0.3"/>
            </ContentPresenter.Effect>
          </ContentPresenter>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

使用方法:

<Label Name="Lbl_IP2"  Style="{StaticResource LabelWithBorder}" Content="3"/>

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