The King
The King

Reputation: 849

Part of text with different color in windows phone 8.1

I am creating a windows phone 8.1 app where app provides the user with a text box. I want to highlight all the hashtags used in the textbox with different color. So as soon as user presses hash(#) on the screen, font color will change till user presses a space key. For example, user enters:

This is a #sample statement.

Font color remains black for the part of text "This is a", but as soon as user presses # key, color changes to red (including the hash itself) and all subsequent characters are in red colored font. So #sample appears in read color. Once user presses a space after the word sample, font color changes back to black and all the remaining text appears to be in black color. How can I achieve this? I tried changing the font color but then it changes for the entire text and not just for the hashtag.

Upvotes: 0

Views: 1193

Answers (2)

Decade Moon
Decade Moon

Reputation: 34306

Why not use a RichEditBox? Here's something I quickly whipped up:

<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;
    }
}

Screenshot

You can obviously optimize it more. It doesn't support formatting pasted text, that's an exercise for you :)

Upvotes: 3

Somdev Singh
Somdev Singh

Reputation: 47

Use this XAML format for text with different color

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

enter image description here

Upvotes: 0

Related Questions