我正在尝试使用WPF RichTextBox,并注意到可以通过循环RichTextBox.Document.Blocks来迭代组成其文档的块。
最好的方法是什么,以获取包围插入符号的块?
我可以获取CaretPosition和每个块的ElementStart和ElementEnd属性,但无法比较它们,因为实际字符偏移量未公开,除非我漏掉了一些明显的东西。
我正在尝试使用WPF RichTextBox,并注意到可以通过循环RichTextBox.Document.Blocks来迭代组成其文档的块。
最好的方法是什么,以获取包围插入符号的块?
我可以获取CaretPosition和每个块的ElementStart和ElementEnd属性,但无法比较它们,因为实际字符偏移量未公开,除非我漏掉了一些明显的东西。
var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
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);
}
以上答案可能适用于WPF RTB,但不适用于Silverlight 4.0。 很可能SL不允许访问RTB的文档部分。 因此,您必须通过Reflection完成它....
像这样:
Paragraph currentParagraph = richTextBox1.CaretPosition.Paragraph;
Blocks 属性是 RichTextBox 的内容属性。它是一个段落元素的集合。