【问题标题】:RichTextBox: different color for the first characterRichTextBox:第一个字符的不同颜色
【发布时间】:2016-05-20 16:54:31
【问题描述】:

我在 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

【问题讨论】:

    标签: .net wpf vb.net


    【解决方案1】:

    您的问题是 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
    

    【讨论】:

    • Visual Studio 在 New TextRange(start, [end]).ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red) 中的 New 下给我一个语法错误
    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2015-10-08
    • 2010-12-27
    • 1970-01-01
    • 2014-12-03
    • 2020-02-18
    相关资源
    最近更新 更多