WPF RichTextBox - Selected Block?

隐身守侯 提交于 2019-11-30 23:53:44
var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();

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.

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