11

I have a label bound to the value of a slider.

Content="{Binding Path=Value, ElementName=Slider}"

How do I append a percentage symbol? The value of the slider is already formatted correctly, so when the value is '50', all I need is '50%'.

I know how to do it in code behind but I was hoping to accomplish this in xaml without creating a converter. TIA

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Brad
  • 1,187
  • 3
  • 23
  • 44

5 Answers5

20

This works fine for me (tested in Kaxaml):

<StackPanel>  
  <Slider Minimum="0" Maximum="100" x:Name="slider" />
  <TextBlock Text="{Binding Path=Value, ElementName=slider, StringFormat='\{0\}%'}" />
</StackPanel>

Without the backslashes I got an error saying that the % character was invalid in that position.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
  • 2
    I changed the label to a TextBlock and it works. I'll research why a label doesn't allow formatting. Thanks! – Brad Mar 16 '10 at 17:11
7

StringFormat can be used in this format as well

Content="{Binding Path=Value, ElementName=Slider, StringFormat=P2}"

Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64
Satya
  • 71
  • 1
  • 1
7

I had a similar issue and solved it by using this, based on @Wiesel's answer:

<Label Content="{Binding Value, ElementName=Slider}" 
       ContentStringFormat="{}{0}%"/>
Igor Pashchuk
  • 2,455
  • 2
  • 22
  • 29
1

You can use StringFormat like so

Content="{Binding Path=Value, ElementName=Slider, StringFormat='{0}%'}"
Chris
  • 26,744
  • 48
  • 193
  • 345
  • Thanks Chris. I've tried that (and many other configurations) with no luck. Any thoughts what might be happening? – Brad Mar 16 '10 at 16:50
  • That definately works as I have used it myself... What error do you get? What actually gets printed to the screen? – Chris Mar 16 '10 at 16:52
  • No error, it simply shows the digits. ie. '50' The label has no other properties set. – Brad Mar 16 '10 at 16:56
  • 1
    Actually... StringFormat='{0}%' doesn't work but StringFormat='{}{0}%' does? Strange, that! That is to say, it shows the digits only. – Brad Mar 16 '10 at 17:05
1

Here's the solution for WPF >=3.5 SP1:

<Label Content="{Binding Path=Value, ElementName=Slider}" 
       ContentStringFormat="{0}%" />
Mario Gu
  • 505
  • 4
  • 13