Get FontWeight / FontStyle / TextDecorations from WPF RichTextBox

How to determine current text formatting at cursor position in WPF RichTextBox?

+3
source share
4 answers

Try the code below, where rtb is a RichTextBox:

TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
0
source

I would use CaretPosition instead of the start and end of the selection, as if the RichTextBox really had a choice that spans several areas of formatting, you get DependencyProperty.UnsetValue.

TextRange tr = new TextRange (rtb.CaretPosition, rtb.CaretPosition);
object oFont = tr.GetPropertyValue (Run.FontFamilyProperty);
+3
source

TextDecorations, . :

var obj = _myText.GetPropertyValue(Inline.TextDecorationsProperty);

                    if (obj == DependencyProperty.UnsetValue)                   
                        IsTextUnderline = false;// mixed formatting 

                    if (obj is TextDecorationCollection)
                    {
                        var objProper = obj as TextDecorationCollection;

                        if (objProper.Count > 0)                        
                            IsTextUnderline = true; // all underlined                       
                        else                        
                            IsTextUnderline = false; // nothing underlined                   
                    } 
+3

Here is a solution that defines FontWeight, FontStyle, TextDecorations (cross out, underline) and Super- and Subscript.

        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
+1
source

Source: https://habr.com/ru/post/1698276/


All Articles