部分文本颜色更新

时间:2011-03-02 15:41:39

标签: wpf textblock

这就是我的

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

现在在GUI上我将所有三个文本块的文本显示为单行,如:abcdefghi。我想更新部分文本颜色(无论文本是哪个文本块。
假设我想将总文本的40%的颜色更改为红色,将其他颜色的颜色更改为白色。 (也是百分比量太多了)它将通过Binding更新。所以没有文本%和任何特定文本块的硬编码。

完成 - 。How to make text color appear differently using 2 textblock for a single text

1 个答案:

答案 0 :(得分:3)

您可以使用一个TextBlockLinearGradient和一些附加属性执行此操作,只要您不介意字母部分着色。

编辑:我决定写一篇文章,展示附加属性的解决方案,但同时您可以使用简单的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