C# WinUI 3 富文字區塊 RichTextBlock 示範

xaml 靜態指定

在 xaml 中定義 RichTextBlock 最簡單可以使用下列方式:
    
<RichTextBlock>
    <Paragraph>
        文字文字文字
    </Paragraph>
</RichTextBlock>
    

但其實 RichTextBlock 內是由多個段落(Paragraph)組成,而段落中要放入文字還需要透過文字區塊(Run)才可以。只是在 xaml 定義時可以省略 Run 區塊。

完整範例如下:
    
<RichTextBlock>
    <Paragraph>
        段落一
    </Paragraph>
    <Paragraph>
        <Run Foreground="Blue" FontSize="16">
            段落二
        </Run>
        <Run FontWeight="Bold">
            粗體
        </Run>
        <Run FontStyle="Italic">
            斜體
        </Run>
        <Run TextDecorations="Underline">
            底線
        </Run>
    </Paragraph>
</RichTextBlock>
    

C# 動態新增

在 C# 中就不像是 xaml 可以省略文字區塊(Run),一定要將 RichTextBlock, Paragraph, Run 每個都定義好。
基本範例:
    
RichTextBlock richTextBlock = new RichTextBlock();
Paragraph paragraph = new Paragraph(); // 段落
paragraph.Inlines.Add(new Run { Text = "段落一" }); // 加入文字區塊
// 將 RichTextBlock 加入至視窗中
this.Content = richTextBlock;


// 加入至 RichTextBlock 佈局中,替換為自己使用的布局
// RelativePanel.Children.Add(richTextBlock);
    

註: Window 中的 Content 只能有一個元件,如果使用 this.Content = richTextBlock; 的方式會無法顯示其他的元件,最好先加入其他的布局,再使用 Children.Add(richTextBlock) 的方式將 RichTextBlock 加入至布局中。

包含屬性的範例:
    
RichTextBlock richTextBlock = new RichTextBlock();
richTextBlock.Blocks.Add(new Paragraph
{
    Inlines =
    {
        new Run { Text = "段落一" },
    }
});

richTextBlock.Blocks.Add(new Paragraph
{
    Inlines =
    {
        new Run { Text = "段落二", FontSize = 16, Foreground = new SolidColorBrush(Colors.Blue) },
        new Run { Text = "粗體", FontWeight = FontWeights.Bold },
        new Run { Text = "斜體", FontStyle = FontStyle.Italic },
        new Run { Text = "底線", TextDecorations = TextDecorations.Underline },
    }
});

this.Content = richTextBlock;


// 加入至 RichTextBlock 佈局中,替換為自己使用的布局
// RelativePanel.Children.Add(richTextBlock);
    



參考資料:
Microsoft.Learn - RichTextBlock Class

留言