Change Color of Single Letter in Label String?
I have a project in WPF 4 and VB.net. I need to change the color a single letter in a word in a label (the label's content changes quite a bit). I really am not sure if this is possible, but if it is, I'd开发者_开发问答 appreciate help on figuring out how. TY!
Label is a content control so any type of content is permitted inside a label.You can easily do your requirement by something like
<Label>
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="Red" Text="T"/>
<TextBlock Text="ext"/>
</StackPanel>
</Label>
A cleaner way would be using the flow-content-capabilites of a TextBlock:
<Label>
<TextBlock>
<Run Text="L" Foreground="Green"/>
<Run Text="orem Ipsum"/>
</TextBlock>
</Label>
This limits binding a bit though, if that is needed.
The cleanest method i found so far is using a TextEffect
:
<Label>
<TextBlock Text="Search">
<TextBlock.TextEffects>
<TextEffect PositionStart="0" PositionCount="1" Foreground="Red"/>
</TextBlock.TextEffects>
</TextBlock>
</Label>
This colors the "S" red. You can of course bind any of the involved properties if they need to be dynamic.
I just implemented something like this in our project, this will be static though - I'm not sure if that's what you need. You can change the content of the label as often as you need, but it will always have a red * at the end. I added a style to the project like this
<Style x:Key="RequiredFieldLabel"
TargetType="{x:Type Label}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
<TextBlock Text="*"
Foreground="red" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Then you can use this style on a label anywhere in your project.
<Label Content="Enter Name:"
Style="{StaticResource RequiredFieldLabel}" />
精彩评论