我在WPF中有一个RichTextBox(Name="txtGoTo"
),我只需要第一个用红色着色的字符(其余字符用默认的黑色)。
这是我尝试过的(在网上获得),但它不起作用:
Dim rtb As RichTextBox = txtGoTo
Dim Text As String = New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text
If Not String.IsNullOrEmpty(Text) Then
Dim RangeAisle As TextPointer = rtb.Document.ContentStart
Dim RangeShelf As TextPointer = rtb.Document.ContentStart.GetPositionAtOffset(1)
Dim tr As New TextRange(RangeAisle, RangeShelf)
tr.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red)
End If
答案 0 :(得分:0)
您的问题是rtb.Document.ContentStart.GetPositionAtOffset(1)
没有返回首字母。它更像是3
下面的代码将获得第一个字母的位置并更改为红色。
Dim position As TextPointer = rtb.Document.ContentStart
While position IsNot Nothing
If position.GetPointerContext(LogicalDirection.Forward) = TextPointerContext.Text Then
Dim start As TextPointer = position.GetPositionAtOffset(0, LogicalDirection.Forward)
Dim [end] As TextPointer = position.GetPositionAtOffset(1, LogicalDirection.Backward)
New TextRange(start, [end]).ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red)
Exit While
End If
position = position.GetNextContextPosition(LogicalDirection.Forward)
End While