Get FontWeight/FontStyle/TextDecorations from WPF RichTextBox

前端 未结 4 418
渐次进展
渐次进展 2021-01-14 13:02

How can I detect the current text formatting at the cursor position in a WPF RichTextBox?

4条回答
  •  天涯浪人
    2021-01-14 13:31

    Here is a solution that determines FontWeight, FontStyle, TextDecorations (strikethrough, underline) and Super- and Subscripts.

            TextRange textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);
    
            bool IsTextUnderline = false;
            bool IsTextStrikethrough = false;
            bool IsTextBold = false;
            bool IsTextItalic = false;
            bool IsSuperscript = false;
            bool IsSubscript = false;
    
            // determine underline property
            if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Strikethrough))
                IsTextStrikethrough = true; // all underlined   
            else if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline))
                IsTextUnderline = true; // all strikethrough
    
            // determine bold property
            if (textRange.GetPropertyValue(Inline.FontWeightProperty).Equals(FontWeights.Bold))
                IsTextBold = true; // all bold
    
            // determine if superscript or subscript
            if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Subscript))
                IsSubscript = true; // all subscript
            else if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Superscript))
                IsSuperscript = true; // all superscript
    

提交回复
热议问题