1

Here is what i've

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

Now on GUI i show all three textblock's text in single line like : abcdefghi . I want to update the partial text color (irrespective of which textblock the textbelong.
Say i want to change the color of 40% of total text to red and other as white. (also the percentage amount is too variable) It will update by Binding. So no hardcoding for text % and any specific textblock.

Done by -.How to make text color appear differently using 2 textblock for a single text

Community
  • 1
  • 1
Rohit
  • 6,365
  • 14
  • 59
  • 90
  • 2
    why r u using 3 textblocks and not one richTextBox ? – Erez Mar 02 '11 at 15:46
  • you can see the reason in link i've added – Rohit Mar 06 '11 at 16:39
  • You can use a `MultiBinding` to achieve a "x of y" display without using multiple `TextBlock`s. That, plus my technique below will achieve the effect you want, I think. – madd0 Mar 07 '11 at 09:12
  • Actually i've already did this thing but your blog was quite helpful so marking that as answer :) ... – Rohit Mar 08 '11 at 06:39

1 Answers1

3

You can do this with one TextBlock, a LinearGradient and a few attached properties, as long as you don't mind letters being partially colored.

EDIT: I decided to write a post showing the solution with attached properties, but in the meanwhile you could use simple XAML and bindings like so:

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

And if you're interested by the solution using attached properties, you can visit Partially Coloured TextBlock on my blog.

madd0
  • 9,053
  • 3
  • 35
  • 62