I want to format my string binding as Amount is X
where X
is a property bound to a label.
I've seen many examples but the following doesn't work:
<Label Content="{Binding Path=MaxLevelofInvestment,
StringFormat='Amount is {0}'}" />
I've also tried these combinations:
StringFormat=Amount is {0}
StringFormat='Amount is {}{0}'
StringFormat='Amount is \{0\}'
I even tried changing the binding property's datatype to int
, string
and double
. Nothing seems to work. This is a very common use case but doesn't seem to be supported.
Best Answer
The reason this doesn't work is that the
Label.Content
property is of typeObject
, andBinding.StringFormat
is only used when binding to a property of typeString
.What is happening is:
Binding
is boxing yourMaxLevelOfInvestment
value and storing it theLabel.Content
property as a boxed decimal value.ContentPresenter
.ContentTemplate
is not set,ContentPresenter
looks for aDataTemplate
defined for theDecimal
type. When it finds none, it uses a default template.ContentPresenter
presents strings by using the label'sContentStringFormat
property.Two solutions are possible:
Here is how to use Label.ContentStringFormat:
Here is how to use a TextBlock:
Note: For simplicity I omitted one detail in the above explanation: The
ContentPresenter
actually uses its ownTemplate
andStringFormat
properties, but during loading these are automatically template-bound to theContentTemplate
andContentStringFormat
properties of theLabel
, so it seems as if theContentPresenter
is actually using theLabel
's properties.