Label 与 TextBlock 的区别

根据 使用 Microsoft.NET4开发 Windows 应用程序70-511训练包

Label控件和 TextBlock控件的区别是什么? 因为它们都是内容控件,只是显示文本?

81957 次浏览

标签通常支持单行文本输出,而 TextBlock 用于多行文本显示。

例如,在 wpfTextBlock 中有一个属性 TextWrapping,它支持多行输入; Label 没有这个属性。

LabelContentControl,这意味着您可以为它设置任何内容。绝对包括字符串、数字、日期、其他控件、图像、形状等。TextBlock只能处理 strings

TextBlock 不是控件

即使 TextBlock存在于系统中。窗户。控件的命名空间,它不是控件。它直接来源于 FrameworkElement。另一方面,标签来源于 ContentControl。这意味着 Label可以:

  1. 给定一个自定义控件模板(通过 Template属性)。
  2. 显示字符串以外的数据(通过 Content属性)。
  3. 对其内容应用 DataTemplate(通过 ContentTemplate属性)。
  4. 做任何其他 ContentControl能做的事,而 FrameworkElement不能。

    • 禁用时,Label文本为灰色
    • Label支持访问密钥
    • LabelTextBlock重得多

来源

下面是一些更有趣的内容

虽然 TextBlock 和 Label 都用于显示文本,但是它们在封面下是完全不同的。

= > 标签内容控制继承,内容控制是一个基类 能够显示几乎任何可以想象的 UI。

另一方面,文本块直接从 FrameworkElement 框架元素继承,因此错过了从 Control 继承的所有元素的共同行为。 TextBlock 的浅层继承层次结构使得控件比 Label 更轻量级,并且更适合于更简单、非交互的场景。

PS: 但是,如果你想要 钥匙工作,或者想要一个更加灵活的或者图形化的设计,你需要使用 Label。

TextBlock最恼人的特性可能是隐式样式查找行为,其范围仅限于最接近的 DataTemplate。这是非 Control xaml 元素的默认行为。

<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Red"/>
</Style>


<Style TargetType="Label">
<Setter Property="Foreground" Value="Red"/>
</Style>
</StackPanel.Resources>


<ContentControl Content="Test">
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>


<ContentControl Content="Test">
<ContentControl.ContentTemplate>
<DataTemplate>
<Label Content="{Binding}"/>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
</StackPanel>

产生的结果是:

enter image description here

你可以阅读更多关于它的资料。