Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get FontWeight/FontStyle/TextDecorations from WPF RichTextBox

Tags:

.net

wpf

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

like image 866
dmo Avatar asked Dec 23 '22 14:12

dmo


2 Answers

The author of this thread also asked about TextDecorations where you did not provide sample code and its different to use. I post this as a further solution:

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                   
                    } 
like image 182
msfanboy Avatar answered May 13 '23 22:05

msfanboy


I'd use the CaretPosition instead of the selection start and end, as if the RichTextBox actually has a selection that spans multiple areas of formatting you would get DependencyProperty.UnsetValue.

TextRange tr = new TextRange(rtb.CaretPosition, rtb.CaretPosition);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
like image 37
Donnelle Avatar answered May 14 '23 00:05

Donnelle