WPF中让TextBlock每一个字符显示不同的颜色

原文: 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内的字符串:
图片

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9589347.html
今日推荐