【问题标题】:Part of text with different color in windows phone 8.1windows phone 8.1中不同颜色的部分文本
【发布时间】:2025-12-06 23:15:02
【问题描述】:

我正在创建一个 Windows Phone 8.1 应用程序,其中应用程序为用户提供一个文本框。我想用不同的颜色突出显示文本框中使用的所有主题标签。 因此,只要用户在屏幕上按下 hash(#),字体颜色就会改变,直到用户按下空格键。 例如,用户输入:

This is a #sample statement.

文本“This is a”部分的字体颜色保持黑色,但一旦用户按下# 键,颜色就会变为红色(包括哈希本身),并且所有后续字符都为红色字体。 所以#sample 以读取颜色出现。一旦用户在单词样本后按下空格,字体颜色就会变回黑色,并且所有剩余的文本都显示为黑色。 我怎样才能做到这一点?我尝试更改字体颜色,但随后它会更改整个文本,而不仅仅是主题标签。

【问题讨论】:

  • 由于它不是严格意义上的获胜电话答案,我不会将其标记为重复,但this 似乎是一条不错的路线。

标签: c# xaml windows-phone-8.1


【解决方案1】:

为什么不使用 RichEditBox?以下是我快速整理的内容:

<RichEditBox x:Name="tb" TextChanged="tb_TextChanged" />
private void tb_TextChanged(object sender, RoutedEventArgs e)
{
    // we don't want this handler being called as a result of
    // formatting changes being made here
    tb.TextChanged -= tb_TextChanged;

    var doc = tb.Document;
    doc.BatchDisplayUpdates();

    try
    {
        string text;
        doc.GetText(TextGetOptions.None, out text);
        if (text.Length == 0)
            return;

        // check if this word starts with a hash
        var start = doc.Selection.StartPosition - 1;
        while (true)
        {
            if (start < 0 || char.IsWhiteSpace(text[start]))
                return;
            if (text[start] == '#')
                break;
            start--;
        }

        // find the end of the word
        var end = doc.Selection.StartPosition;
        while (start < text.Length && !char.IsWhiteSpace(text[end]))
            end++;

        // set color
        doc.GetRange(start, end).CharacterFormat.ForegroundColor = Colors.RoyalBlue;
    }
    finally
    {
        doc.ApplyDisplayUpdates();
        tb.TextChanged += tb_TextChanged;
    }
}

您显然可以对其进行更多优化。它不支持格式化粘贴的文本,这是你的练习:)

【讨论】:

  • 谢谢。这有帮助。我在 Windows 8.1 手机上发现的唯一问题是,一旦文本颜色变为宝蓝色,空格后它并没有变回黑色。设法修复它。标记为答案。
【解决方案2】:

将此 XAML 格式用于不同颜色的文本

> <TextBlock FontSize="30">
>             <Run Foreground="Red" Text="Hi "></Run>
>             <Run Foreground="Green" Text="This "></Run>
>             <Run Foreground="Blue" Text="is "></Run> 
              <Run Foreground="White" Text="Color."></Run> </TextBlock>

【讨论】:

  • 这没有回答问题,TextBlock 不可编辑。
最近更新 更多