RichTextBox for UWP
書式設定機能
RichTextBox の使い方 > メニューとコマンド > カスタムコマンドバーを作成する > 書式設定機能

次のコードスニペットは、書式設定機能に使用されるコードを示しています。

前景色

C#
コードのコピー
rtb.Selection.Foreground = new SolidColorBrush(Colors.Red);

強調表示色(背景)

C#
コードのコピー
rtb.Selection.InlineBackground = new SolidColorBrush(Colors.Yellow);

太字の切り替え

C#
コードのコピー
if (rtb.Selection.FontWeight != null && rtb.Selection.FontWeight.Value.Weight == FontWeights.Bold.Weight)
{
    rtb.Selection.FontWeight = FontWeights.Normal;
}
else
{
    rtb.Selection.FontWeight = FontWeights.Bold;
}

斜体の切り替え

C#
コードのコピー
if (rtb.Selection.FontStyle != null && rtb.Selection.FontStyle == FontStyle.Italic)
{
    rtb.Selection.FontStyle = FontStyle.Normal;
}
else
{
    rtb.Selection.FontStyle = FontStyle.Italic;
}

下線の切り替え

C#
コードのコピー
var range = rtb.Selection;
var collection = new C1TextDecorationCollection();
if (range.TextDecorations == null)
{
    collection.Add(C1TextDecorations.Underline[0]);
}
else if (!range.TextDecorations.Contains(C1TextDecorations.Underline[0]))
{
    foreach (var decoration in range.TextDecorations)
        collection.Add(decoration); 

    collection.Add(C1TextDecorations.Underline[0]);
}
else
{
    foreach (var decoration in range.TextDecorations)
        collection.Add(decoration); 

    collection.Remove(C1TextDecorations.Underline[0]);
    if (collection.Count == 0)
        collection = null;
}
range.TextDecorations = collection;

書式のクリア

C#
コードのコピー
rtb.Selection.InlineBackground = null;
rtb.Selection.Foreground = rtb.Foreground;
rtb.Selection.FontWeight = FontWeights.Normal;
rtb.Selection.FontStyle = FontStyle.Normal;
rtb.Selection.TextDecorations = null;