1. 程式人生 > >WPF中讓TextBlock每一個字符顯示不同的顏色

WPF中讓TextBlock每一個字符顯示不同的顏色

red set ref 後臺 target wid ffffff 包含 訪問

原文:WPF中讓TextBlock每一個字符顯示不同的顏色

XAML代碼:

<TextBlock x:Name="tb">
              <Run Foreground="Red">R</Run>
              <Run Foreground="Green">G</Run>
              <Run Foreground="Blue">B</Run>
              <Run Text="Gradient">
                 <
Run.Foreground> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF000000" Offset="0"/> <GradientStop Color="#FFFFFFFF" Offset="1"/> </LinearGradientBrush> </
Run.Foreground> </Run> </TextBlock>

在後臺的邏輯代碼中應訪問TextBlock的Inlines集合來得到它所包含的字串..如果你用Text屬性是取不到值的..

CS代碼:

string str1 = this.tb.Text;
string str2 = "";
foreach (Run r in tb.Inlines)
{
    str2 += r.Text;
}
MessageBox.Show("str1:["+str1+"]         str2:["+str2+"]");

運行結果:

TextBlock的顯示效果:技術分享圖片

顯示TextBlock內的字符串:
技術分享圖片

WPF中讓TextBlock每一個字符顯示不同的顏色