Wpf – binding stringformat on label using string literal

string-formattingwpfxaml

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.

Best Answer

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 {