- WPF 教程
- WPF - 首頁
- WPF - 概述
- WPF - 環境設定
- WPF - Hello World
- WPF - XAML 概述
- WPF - 元素樹
- WPF - 依賴屬性
- WPF - 路由事件
- WPF - 控制元件
- WPF - 佈局
- WPF - 佈局巢狀
- WPF - 輸入
- WPF - 命令列
- WPF - 資料繫結
- WPF - 資源
- WPF - 模板
- WPF - 樣式
- WPF - 觸發器
- WPF - 除錯
- WPF - 自定義控制元件
- WPF - 異常處理
- WPF - 本地化
- WPF - 互動
- WPF - 2D 圖形
- WPF - 3D 圖形
- WPF - 多媒體
- WPF 有用資源
- WPF - 快速指南
- WPF - 有用資源
- WPF - 討論
WPF - 文字塊
TextBlock 是一種輕量級控制元件,用於顯示少量只讀文字。TextBlock 類的層次繼承如下:
TextBlock 類常用屬性
| 序號 | 屬性和描述 |
|---|---|
| 1 | ContentEnd 獲取 TextBlock 中文字內容末尾的 TextPointer 物件。 |
| 2 | ContentStart 獲取 TextBlock 中文字內容開頭的 TextPointer 物件。 |
| 3 | IsTextSelectionEnabled 獲取或設定一個值,該值指示是否在 TextBlock 中啟用文字選擇,可以透過使用者操作或呼叫與選擇相關的 API 來啟用。 |
| 4 | IsTextSelectionEnabledProperty 標識 IsTextSelectionEnabled 依賴屬性。 |
| 5 | LineHeight 獲取或設定每行內容的高度。 |
| 6 | MaxLines 獲取或設定在 TextBlock 中顯示的最大文字行數。 |
| 7 | SelectedText 獲取選定文字的文字範圍。 |
| 8 | SelectionEnd 獲取 TextBlock 中選定文字的結束位置。 |
| 9 | SelectionHighlightColor 獲取或設定用於突出顯示選定文字的畫筆。 |
| 10 | SelectionStart 獲取 TextBlock 中選定文字的起始位置。 |
| 11 | Text 獲取或設定 TextBlock 的文字內容。 |
| 12 | TextAlignment 獲取或設定一個值,該值指示文字內容的水平對齊方式。 |
| 13 | TextTrimming 獲取或設定當內容超出內容區域時要使用的文字修剪行為。 |
| 14 | TextWrapping 獲取或設定 TextBlock 如何換行文字。 |
TextBlock 類常用事件
| 序號 | 事件和描述 |
|---|---|
| 1 | ContextMenuOpening 當系統處理顯示上下文選單的互動時發生。 |
| 2 | SelectionChanged 當文字選擇發生更改時發生。 |
TextBlock 類常用方法
| 序號 | 方法和描述 |
|---|---|
| 1 | Focus 使 TextBlock 獲得焦點,就像它是一個常規的可獲得焦點的控制元件一樣。 |
| 2 | Select 選擇 TextBlock 中的一段文字。 |
| 3 | SelectAll 選擇 TextBlock 中的全部內容。 |
示例
- 讓我們建立一個帶有 WPFTextBlockControl 的新 WPF 專案。
- 從工具箱中拖動一個文字塊。
- 從屬性視窗更改文字塊的背景顏色。
- 以下示例顯示了在 XAML 應用程式中使用 TextBlock 的方法。
- 以下是建立具有某些屬性的 TextBlock 的 XAML 程式碼。
<Window x:Class = "WPFTextBlockControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFTextBlockControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<TextBlock FontFamily = "Verdana"
LineStackingStrategy = "MaxHeight" LineHeight = "10" Width = "500"
TextWrapping = "Wrap" Background = "#FFE2B1B1" Margin = "48,8,48,10">
Use the <Run FontSize = "30">LineStackingStrategy</Run> property to determine how
a line box is created for each line. A value of <Run FontSize = "20">MaxHeight</Run>
specifies that the stack height is the smallest value that contains all the inline
elements on that line when those elements are properly aligned. A value of <Run
FontSize = "20"> BlockLineHeight</Run> specifies that the stack height is
determined by the block element LineHeight property value.
</TextBlock>
</Grid>
</Window>
編譯並執行以上程式碼後,將產生以下輸出:
我們建議您執行以上示例程式碼,並嘗試 TextBlock 類的其他屬性和事件。