2014-12-02 44 views
0

我正在創建一個Windows Phone 8.1應用程序,其中應用程序向用戶提供一個文本框。我想用不同的顏色突出顯示文本框中使用的所有hashtags。 因此,只要用戶在屏幕上按哈希(#),字體顏色將會改變,直到用戶按下空格鍵。 例如,用戶輸入:在Windows Phone 8.1中使用不同顏色的文本的一部分

This is a #sample statement. 

字體顏色保持黑色文本的部分「這是一個」,但只要用戶按下#鍵,顏色變爲紅色(包括散列本身)和所有後續字符以紅色字體顯示。 所以#sample以讀取顏色出現。一旦用戶在單詞樣本之後按下空格,字體顏色將變回黑色,其餘所有文字將顯示爲黑色。 我該如何做到這一點?我嘗試改變字體顏色,但是它改變了整個文本,而不僅僅是標籤。

+0

因爲它不是一個贏得電話答案我不會將它標記爲重複,但[this](http://stackoverflow.com/questions/3707120/how-to-the-rich-text-from-the-rich-text-it)看起來像一條不錯的路線。 – 2014-12-02 15:20:23

回答

0

用於文本此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> 

enter image description here

+0

這不會回答問題,TextBlock不可編輯。 – kennyzx 2014-12-02 12:22:02

3

爲什麼不使用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; 
    } 
} 

Screenshot

可以很明顯的優化更多。它不支持格式化粘貼文本,這是一個練習:)

+0

謝謝。這有幫助。我在windows 8.1手機上發現的唯一問題是,一旦文本顏色變成皇家藍色,在空間後它不會變回黑色。管理解決它。標記爲答案。 – 2014-12-05 18:52:38

相關問題