WPF RichTextBox - Selected Block?

[亡魂溺海] 提交于 2019-11-30 18:32:31

问题


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

What is the best way to get the Block that surrounds the caret?

I can get the CaretPosition and the ElementStart and ElementEnd properties of each block but can't see how to compare them because the actual character offsets are not exposed unless I am missing something obvious.


回答1:


var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();



回答2:


Answer above probably works in WPF RTB but not in Silverlight 4.0. Most likely SL doesn't allow access to the Document protion of the RTB. So you have to do it via Reflection....

Something like this:

  • Set up a TextSelectionChanged Event Handler
  • Grab the TextSelection Pointer and find the Start TextPointer
  • Grab the TextSelection.Start.Parent item
  • Find out if it is of type paragraph
  • Parse the Paragraph.Inlines
  • Look for type of InlineUIContainer you need a cast it accordingly.



回答3:


In Silverlight5 get the properties to be used to update a 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);
}


来源:https://stackoverflow.com/questions/2553090/wpf-richtextbox-selected-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!