标签内容上的 WPF StringFormat [英] WPF StringFormat on Label Content
问题描述
我想将我的字符串绑定格式化为 Amount is X
其中 X
是绑定到标签的属性.
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}'}" />
我也尝试过这些组合:
StringFormat=Amount is {0}
StringFormat='Amount is {}{0}'
StringFormat='Amount is {0}'
我什至尝试将绑定属性的数据类型更改为 int
、string
和 double
.似乎没有任何效果.这是一个非常常见的用例,但似乎不受支持.
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.
推荐答案
这不起作用的原因是 Label.Content
属性是 Object
类型,并且 Binding.StringFormat
仅在绑定到 String
类型的属性时使用.
The reason this doesn't work is that the Label.Content
property is of type Object
, and Binding.StringFormat
is only used when binding to a property of type String
.
正在发生的事情是:
Binding
将您的MaxLevelOfInvestment
值装箱并将其存储为Label.Content
属性作为装箱十进制值.- 标签控件有一个包含
ContentPresenter
的模板. - 由于未设置
ContentTemplate
,ContentPresenter
会查找为Decimal
类型定义的DataTemplate
.如果没有找到,则使用默认模板. ContentPresenter
使用的默认模板通过使用标签的ContentStringFormat
属性呈现字符串.
- The
Binding
is boxing yourMaxLevelOfInvestment
value and storing it theLabel.Content
property as a boxed decimal value. - The Label control has a template that includes a
ContentPresenter
. - Since
ContentTemplate
is not set,ContentPresenter
looks for aDataTemplate
defined for theDecimal
type. When it finds none, it uses a default template. - The default template used by the
ContentPresenter
presents strings by using the label'sContentStringFormat
property.
有两种可能的解决方案:
Two solutions are possible:
- 使用 Label.ContentStringFormat 而不是 Binding.StringFormat,或者
- 使用 String 属性,例如 TextBlock.Text 而不是 Label.Content
以下是如何使用 Label.ContentStringFormat:
Here is how to use Label.ContentStringFormat:
<Label Content="{Binding Path=MaxLevelofInvestment}" ContentStringFormat="Amount is {0}" />
以下是使用 TextBlock 的方法:
Here is how to use a TextBlock:
<TextBlock Text="{Binding Path=MaxLevelofInvestment, StringFormat='Amount is {0}'}" />
注意:为了简单起见,我在上面的解释中省略了一个细节:ContentPresenter
实际上使用了它自己的 Template
和 StringFormat
属性,但在加载这些自动模板绑定到 Label
的 ContentTemplate
和 ContentStringFormat
属性,所以看起来好像 ContentPresenter
实际上是在使用 Label
的属性.
Note: For simplicity I omitted one detail in the above explanation: The ContentPresenter
actually uses its own Template
and StringFormat
properties, but during loading these are automatically template-bound to the ContentTemplate
and ContentStringFormat
properties of the Label
, so it seems as if the ContentPresenter
is actually using the Label
's properties.
这篇关于标签内容上的 WPF StringFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!