2011-03-02 161 views
1

這裏是我部分文本顏色更新

<StackPanel> 
    <TextBlock> abc </TextBlock> 
    <Textblock> def </Textblock> 
    <Textblock> ghi </Textblock> 
</Stackpanel> 

現在GUI上顯示我像一條線全部三種文字塊的文字:ABCDEFGHI。我想更新部分文本的顏色(不管文本塊是哪一個文本塊)
假設我想將總文本的40%的顏色改爲紅色,其他顏色爲白色(也是百分比數量太多)它會更新可以通過綁定因此,沒有硬編碼的文本%和任何特定的文本塊

所做 - How to make text color appear differently using 2 textblock for a single text

+2

爲什麼你使用3個文本塊而不是一個richTextBox? – Erez 2011-03-02 15:46:06

+0

你可以在我添加的鏈接中看到原因 – Rohit 2011-03-06 16:39:05

+0

你可以使用'MultiBinding'來實現「x的y」顯示,而不使用多個'TextBlock'。那麼,加上我下面的技巧將達到你想要的效果,我想。 – madd0 2011-03-07 09:12:19

回答

3

你可以用一個TextBlock,一個LinearGradient和幾個附加屬性做到這一點,只要你不頭腦字母部分着色

編輯:我決定寫出與附加屬性的解決方案後,但在此期間,你可以使用簡單的XAML和綁定像這樣:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="auto" /> 
     <RowDefinition Height="auto" /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 

    <TextBlock FontSize="34" FontWeight="Bold" 
       Text="{Binding Value, ElementName=slider, StringFormat={}{0:p0} of this text is coloured}"> 
     <TextBlock.Foreground> 
      <LinearGradientBrush EndPoint="1 0"> 
       <GradientStop Color="BurlyWood" /> 
       <GradientStop Color="BurlyWood" Offset="{Binding Value, ElementName=slider}" /> 
       <GradientStop Color="Beige" Offset="{Binding Value, ElementName=slider}" /> 
       <GradientStop Color="Beige" Offset="1" /> 
      </LinearGradientBrush> 
     </TextBlock.Foreground> 
    </TextBlock> 

    <Slider x:Name="slider" Grid.Row="1" Minimum="0" Maximum="1" Value="0.4" /> 
</Grid> 

如果你有興趣通過使用附加屬性的解決方案,可以請在我的博客上訪問Partially Coloured TextBlock

+0

+1爲您的博客:) ...尼斯 – Rohit 2011-03-07 06:32:50