一、基本介绍
作用:
TextBlock 是 WPF 中的一个用于显示只读文本的控件,适用于显示标题、标签、说明文字等。
UI设计技巧:
- 使用不同的 FontSize 和 FontWeight 来区分文本的重要性。
- 通过 Foreground 属性设置文本颜色,以匹配整体设计风格。
- 使用 Margin 和 Padding 属性来调整文本的布局。
样式技巧:
- 定义和应用样式(Styles)以统一文本的外观。
- 使用 Trigger 和 Setter 在特定条件下改变 TextBlock 的样式。
二、基础 XAML 写法:
<TextBlock Text="Hello, WPF!" FontSize="14" FontWeight="Bold" Margin="5" />
属性及其值类型:
- Text(String):要显示的文本。
- FontSize(Double):字体大小。
- FontWeight(FontWeight):字体的粗细,如 Normal 或 Bold。
- Foreground(Brush):文本颜色。
- Margin(Thickness):控件的外边距。
事件:
TextBlock 支持的事件不多,常见的是鼠标事件,如 MouseLeftButtonDown。
事件介绍及代码举例:
<TextBlock Text="Click me!" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" />
代码behind:
private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBlock textBlock = sender as TextBlock;
if (textBlock != null)
{
textBlock.Text = "Clicked!";
}
}
使用技巧:
- 使用 Inlines 属性来创建包含多种格式文本的 TextBlock。
<TextBlock>
<Run FontWeight="Bold">Bold</Run>
<Run FontStyle="Italic">Italic</Run>
</TextBlock>
三、高级用法 使用 Inlines 属性创建富文本:
<TextBlock>
<Run Foreground="Red">Red</Run>
<LineBreak />
<Run Foreground="Green">Green</Run>
<LineBreak />
<Run Foreground="Blue">Blue</Run>
</TextBlock>
四、进阶技巧 数据绑定和转换器:
<TextBlock Text="{Binding Path=DateTime, StringFormat='{}{0:dddd, dd MMMM yyyy}', Converter={StaticResource MyDateTimeConverter}}" />
VisualState 和 VisualStateManager:
<TextBlock>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Black" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
五、注意事项
- 避免在 TextBlock 中放置过长的文本,以免影响性能和用户体验。
- 确保文本在 TextBlock 中清晰可见,避免与其他控件重叠。
- 如果需要用户输入文本,请使用 TextBox 控件而不是 TextBlock。
- 考虑到可访问性,确保文本颜色与背景颜色对比度足够高。