2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WPF RitchTextBoxで特定の単語に色をつけたい

Last updated at Posted at 2024-09-20

RitchTextBoxをよくわかっていなくて無駄に時間を食ってしまったので書き留めておきます

private void EmphasizePlaceholder(string targetWord)
{
    // 最初のパラグラフを取得
    var current = MessageField.Document.ContentStart;

    // パラグラフ?に分かれて収まっているのでパラグラフ毎に処理する
    while(current != null)
    {
    	// テキスト以外はスルー
        if(current.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) 
        {

            var text = current.GetTextInRun(LogicalDirection.Forward);
    
            // 今回は1単語毎?にパラグラフに分かれるから1つだけということで
            // 全角のワードとかだったら複数あることを想定したほうが良い
            var index = text.IndexOf(targetWord);
    
            if(index != -1)
            {
                var start = current.GetPositionAtOffset(index);
                var end = current.GetPositionAtOffset(index + targetWord.Length);
    
                // 色を変更する範囲を指定
                var range = new TextRange(start, end);
    
                // 色を変更
                range.ApplyPropertyValue(TextElement.ForegroundProperty, placeholderColor);
    
            }
        }

        // 次のパラグラフに
        current = current.GetNextContextPosition(LogicalDirection.Forward);
    }

}

※入力中随時反映したいときTextChangedに書いてしまうとApplyPropertyValueでテキストが変更された扱いになり無駄に何度も再帰的に呼び出すことになるからKeyUpとかの方が良い?

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?