WPF RichTextBox - selected block?

I am experimenting with WPF RichTextBox and notice that I can repeat through the blocks that make up his document by looping through RichTextBox.Document.Blocks.

What is the best way to get the block that surrounds the carriage?

I can get the CaretPosition and ElementStart and ElementEnd properties of each block, but I don’t see how to compare them, because the actual character offsets are not displayed unless I see something obvious.

+3
source share
3 answers
var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
+8
source

, , WPF RTB, Silverlight 4.0. , SL RTB. Reflection....

- :

  • TextSelectionChanged
  • TextSelection Start TextPointer
  • TextSelection.Start.Parent
  • , paragraph
  • .
  • InlineUIContainer, .
+1

In Silverlight5, get the properties that will be used to update the toolbar:

private void rtb_SelectionChanged(object sender, RoutedEventArgs e)
{
    TextSelection ts = rtb.Selection;
    object property;

    property =  ts.GetPropertyValue(Run.FontWeightProperty);
    System.Windows.FontWeight fontWeight = property is System.Windows.FontWeight ? (FontWeight)property : FontWeights.Normal;

    property = ts.GetPropertyValue(Run.FontStyleProperty);
    System.Windows.FontStyle fontStyle = property is System.Windows.FontStyle ? (FontStyle)property : FontStyles.Normal;

    TextDecorationCollection textDecorations = ts.GetPropertyValue(Run.TextDecorationsProperty) as TextDecorationCollection;
    bool isUnderlined = textDecorations != null;

    double? fontSize = ts.GetPropertyValue(Run.FontSizeProperty) as double?;
    SolidColorBrush foreground = ts.GetPropertyValue(Run.ForegroundProperty) as SolidColorBrush;
    Color foregroundColor = foreground != null ? foreground.Color : Colors.Black;

    System.Diagnostics.Debug.WriteLine("fontweight:{0}, fontStyle:{1}, Underline:{2}, size:{3}, color:{4}", 
        fontWeight,
        fontStyle,
        isUnderlined,
        fontSize, 
        foregroundColor);

    if (fontSize.HasValue)
        SetToolbarFontSize(fontSize.Value);

    SetToolbarFontColor(foregroundColor);
}
0
source

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


All Articles