Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 286
CodeMouse92 Avatar asked May 21 '11 20:05

CodeMouse92


3 Answers

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>
like image 95
biju Avatar answered Oct 18 '22 23:10

biju


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.

like image 24
H.B. Avatar answered Oct 18 '22 21:10

H.B.


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}" />
like image 20
javajavajavajavajava Avatar answered Oct 18 '22 21:10

javajavajavajavajava