首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 Store Apps 開發教學 (1):文本控件完全指南

     編輯:關於.NET

前言

文字顯示與輸入是 App 的基礎。Windows 8 Store Apps 提供六大文本控件:TextBlock、TextBox、PasswordBox、RichEditBox、RichTextBlock、RichTextBlockOverflow。本篇從基本屬性到進階排版、編輯、搜尋、多欄流動佈局,完整涵蓋各控件實戰技巧。

一、TextBlock - 純文字顯示

輕量級唯讀文字元素,支援豐富格式化:

  • 字體:FontFamily/FontSize/FontWeight/FontStyle/FontStretch
  • 對齊/換行:TextAlignment/TextWrapping
  • 行高策略:LineHeight/LineStackingStrategy (MaxHeight/BlockLineHeight/BaselineToBaseline)
  • 字元間距:CharacterSpacing (單位 1/1000 em)
  • 溢出修剪:TextTrimming="WordEllipsis"
  • 流向:FlowDirection (LTR/RTL)
  • 文字選取:IsTextSelectionEnabled + SelectionChanged 事件
  • 內聯元素:Inlines 集合 (Run/Span/Bold/Italic/Underline/LineBreak)

範例:多種格式化展示

<TextBlock Text="TextBlock &quot;的常用屬性&quot;" TextAlignment="Left" Foreground="Blue"
           FontFamily="微軟雅黑" FontSize="24" FontWeight="Bold" FontStyle="Italic"
           FontStretch="Normal" TextWrapping="Wrap" />
<TextBlock FontSize="24" CharacterSpacing="100" LineStackingStrategy="MaxHeight" LineHeight="100">
    <TextBlock.Inlines>
        <Run Foreground="Red">Run</Run>
        <Span Foreground="Green">Span</Span>
        <LineBreak />
        <Bold>Bold</Bold>
        <Italic>Italic</Italic>
        <Underline>Underline</Underline>
    </TextBlock.Inlines>
</TextBlock>
<TextBlock FontSize="24" Text="abcdefghijklmnopqrstuvwxyz" Width="200" TextTrimming="WordEllipsis" />
<TextBlock FontSize="24" Text="abcdefg" Width="200" FlowDirection="RightToLeft" />
<TextBlock FontSize="24" Name="lblSource" IsTextSelectionEnabled="True" SelectionChanged="txt_SelectionChanged_1">
    <TextBlock.Inlines><Run>abcdefg</Run><LineBreak /><Run>hijklmn</Run><LineBreak /><Run>opqrst</Run></TextBlock.Inlines>
</TextBlock>
<TextBlock FontSize="24" Name="lblCopy" />

後台取得選取文字

private void txt_SelectionChanged_1(object sender, RoutedEventArgs e) {
    lblCopy.Text = lblSource.SelectedText;
}

二、TextBox - 文字輸入框

單行/多行編輯,支援虛擬鍵盤 (SIP) 類型切換:

  • AcceptsReturn/TextWrapping:多行模式
  • MaxLength/IsReadOnly/SelectedText
  • InputScope:如 Number、ChineseFullWidth 等
  • Select(start, length)/SelectAll()/GetRectFromCharacterIndex:程式化選取與測量

範例:基本設定與 InputScope 程式化指定

<TextBox Name="txtDemo" AcceptsReturn="True" TextWrapping="Wrap" MaxLength="50"
         TextAlignment="Center" Width="200" Height="100" Text="webabcd" Loaded="txt_Loaded_1" />
<TextBox Name="txtReadOnly" IsReadOnly="True" Text="{Binding SelectedText, ElementName=txtDemo}" Width="200" Height="100" Margin="0 10 0 0" />
<TextBox InputScope="Number" FlowDirection="RightToLeft" HorizontalAlignment="Left" Margin="0 10 0 0" />
<TextBox Name="txtInputScope" HorizontalAlignment="Left" Margin="0 10 0 0" KeyDown="txtInputScope_KeyDown_1"/>

後台邏輯

private void txt_Loaded_1(object sender, RoutedEventArgs e) {
    txtDemo.Focus(FocusState.Programmatic);
    txtDemo.Select(3, 4); // 選取第 3 字起長度 4
}
void TextBoxDemo_Loaded(object sender, RoutedEventArgs e) {
    InputScope scope = new InputScope();
    scope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.ChineseFullWidth });
    txtInputScope.InputScope = scope;
}
private void txtInputScope_KeyDown_1(object sender, KeyRoutedEventArgs e) {
    if (e.Key == VirtualKey.Enter) txtReadOnly.Focus(FocusState.Programmatic); // 收起鍵盤
}

三、PasswordBox - 密碼輸入框

  • Password:取得明文密碼
  • PasswordChar:遮罩字元 (預設 ●)
  • IsPasswordRevealButtonEnabled:顯示/隱藏切換按鈕
<PasswordBox Width="200" HorizontalAlignment="Left" MaxLength="16" IsPasswordRevealButtonEnabled="True" />

四、RichEditBox - 富文本編輯器

支援格式化編輯 (粗體、斜體)、搜尋高亮、RTF/HTML 匯入匯出。核心 API:Document.Selection、ITextSelection、ITextCharacterFormat、ITextRange.FindText。

範例:簡易編輯器 (粗體/斜體/搜尋高亮)

<StackPanel Orientation="Horizontal">
    <Button Name="btnBold" Content="加粗" Click="btnBold_Click_1" Margin="0 0 10 0" />
    <Button Name="btnItalic" Content="斜體" Click="btnItalic_Click_1" Margin="0 0 10 0" />
    <TextBox Name="txtSearch" Width="200" Margin="0 0 10 0" />
    <Button Name="btnSearch" Content="搜索" Click="btnSearch_Click_1" />
</StackPanel>
<RichEditBox x:Name="txtEditor" Width="320" Height="240" HorizontalAlignment="Left" Margin="0 10 0 0" />

後台實作

private void btnItalic_Click_1(object sender, RoutedEventArgs e) {
    ITextSelection sel = txtEditor.Document.Selection;
    if (sel != null) {
        ITextCharacterFormat fmt = sel.CharacterFormat;
        fmt.Italic = FormatEffect.Toggle;
        sel.CharacterFormat = fmt;
    }
}
private void btnBold_Click_1(object sender, RoutedEventArgs e) {
    ITextSelection sel = txtEditor.Document.Selection;
    if (sel != null) {
        ITextCharacterFormat fmt = sel.CharacterFormat;
        fmt.Bold = FormatEffect.Toggle;
        sel.CharacterFormat = fmt;
    }
}
List<ITextRange> _highlightedWords = new List<ITextRange>();
private void btnSearch_Click_1(object sender, RoutedEventArgs e) {
    // 清除舊高亮
    foreach (var r in _highlightedWords) {
        var cf = r.CharacterFormat; cf.BackgroundColor = Colors.Transparent; r.CharacterFormat = cf;
    }
    _highlightedWords.Clear();
    // 全文搜尋並高亮
    ITextRange range = txtEditor.Document.GetRange(0, TextConstants.MaxUnitCount);
    range.Move(0, 0);
    bool found = true;
    while (found) {
        if (range.FindText(txtSearch.Text, TextConstants.MaxUnitCount, FindOptions.None) < 1) found = false;
        else {
            _highlightedWords.Add(range.GetClone());
            var cf = range.CharacterFormat; cf.BackgroundColor = Colors.Yellow; range.CharacterFormat = cf;
        }
    }
}

五、RichTextBlock - 富文本顯示與多欄流動

唯讀但支援複雜排版:Blocks (Paragraph)、Inlines、InlineUIContainer 嵌入 UI 元素 (如圖片)、TextIndent 首行縮進。配合 RichTextBlockOverflow 實現多欄/跨頁流動。

範例:嵌入圖片與長文本

<RichTextBlock FontSize="14.667" HorizontalAlignment="Left">
    <RichTextBlock.Blocks>
        <Paragraph TextIndent="20">Windows 8是由微軟公司開發的...</Paragraph>
        <Paragraph>
            <InlineUIContainer>
                <StackPanel HorizontalAlignment="Left">
                    <TextBlock Text="顯示一張圖片" />
                    <Image Source="/Assets/Logo.png" Width="100" Height="100" />
                </StackPanel>
            </InlineUIContainer>
        </Paragraph>
    </RichTextBlock.Blocks>
</RichTextBlock>

六、RichTextBlockOverflow - 文字溢出延續容器

透過 OverflowContentTarget 串聯多個 Overflow 區域,實現報紙式多欄佈局或分頁列印。

範例:三欄流動佈局

<StackPanel Orientation="Horizontal">
    <RichTextBlock Width="200" Height="100" OverflowContentTarget="{Binding ElementName=txtOverflow}">
        <Paragraph>一打開Windows 8計算機...(長文本)</Paragraph>
    </RichTextBlock>
    <RichTextBlockOverflow Name="txtOverflow" Width="200" Height="100"
                           OverflowContentTarget="{Binding ElementName=txtOverflow2}" Margin="20 0 0 0" />
    <RichTextBlockOverflow Name="txtOverflow2" Width="200" Height="100"
                           OverflowContentTarget="{Binding ElementName=txtOverflow3}" Margin="20 0 0 0" />
    <RichTextBlockOverflow Name="txtOverflow3" Width="200" Height="100" Margin="20 0 0 0" />
</StackPanel>

總結

從簡單的 TextBlock 到專業的 RichEditBox/RichTextBlock,Windows 8 Store Apps 提供完整的文本處理棧。根據場景選擇:唯讀顯示用 TextBlock/RichTextBlock,單行輸入用 TextBox/PasswordBox,富文本編輯用 RichEditBox,多欄排版用 RichTextBlock+Overflow。完整原始碼請參考 源碼下載。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved