WPF RichTextBox - 选定块?

3

我正在尝试使用WPF RichTextBox,并注意到可以通过循环RichTextBox.Document.Blocks来迭代组成其文档的块。

最好的方法是什么,以获取包围插入符号的块?

我可以获取CaretPosition和每个块的ElementStart和ElementEnd属性,但无法比较它们,因为实际字符偏移量未公开,除非我漏掉了一些明显的东西。

4个回答

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

谢谢Matt。正是我想要的。 - Alan Spark

0
在Silverlight5中,获取要用于更新工具栏的属性:
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

以上答案可能适用于WPF RTB,但不适用于Silverlight 4.0。 很可能SL不允许访问RTB的文档部分。 因此,您必须通过Reflection完成它....

像这样:

  • 设置TextSelectionChanged事件处理程序
  • 获取TextSelection指针并找到起始TextPointer
  • 抓取TextSelection.Start.Parent项
  • 查找其是否为段落类型
  • 解析Paragraph.Inlines
  • 查找所需的InlineUIContainer类型,并进行相应的转换。

1
谢谢。我不再使用WPF了。最终我意识到需要跨越太多障碍,所以我回到了WinForms... - Alan Spark

-1
Paragraph currentParagraph = richTextBox1.CaretPosition.Paragraph;

这段代码将返回一个"段落对象"而不是"区块对象",但由于RichTextBox中的区块通常是段落,因此这不会造成任何问题。

MS 文档:

Blocks 属性是 RichTextBox 的内容属性。它是一个段落元素的集合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接