Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf - binding stringformat on label using string literal

I've binded the tooltip of a slider control to it's Value property and i'm trying to use StringFormat to make it display "Current Value {0} of 10" where the {0} is the Value property. Below is one of the various things I tried when trying to figure this out.

<Slider.ToolTip>
  <Label>
    <Label.Content>
      <Binding StringFormat="Current Value {0} of 10"
               ElementName="DebugLevelSlider"
               Path="Value" />
    </Label.Content>
  </Label>
</Slider.ToolTip>

I am having issues finding examples online of how to use stringformat with string literals such as mine above. I see a lot of stringformat date/time/currency format conversion. I think I have a way to do this with a multibinding but it just seems like an extra amount of work than necessary. I hope that for string literal formatting I still do not have to write a custom converter.

In my app I find myself using a lot of extra labels next to items so getting an understanding in the stringformat will hopefully let me eliminate some of those unnecessary labels.

like image 663
TWood Avatar asked Oct 19 '10 14:10

TWood


2 Answers

Label.Content is object so you can't use Binding.StringFormat there as the binding's target type must be string in order for it to work.

Two work arounds are: use TextBlock instead of Label and bind the Text property.

Use Label.ContentStringFormat i.e.

<Label ContentStringFormat="Current Value {0} of 10" Content={Binding ...} />

You only need to escape the string with {} if your first character is a {

like image 152
Guillermo Ruffino Avatar answered Oct 24 '22 09:10

Guillermo Ruffino


For the ToolTip, you can check out WPF binding with StringFormat doesn't work on ToolTips.

As far as the StringFormat you specified above, you have to escape your string.

StringFormat="{}Current Value {0} of 10"

Here are a bunch of StringFormat examples. http://blogs.msdn.com/b/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx

like image 27
a_hardin Avatar answered Oct 24 '22 11:10

a_hardin