问题描述
我要格式化我的字符串作为金额绑定是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}'}" />
我也试过这些组合:
I've also tried these combinations:
StringFormat=Amount is {0}
StringFormat='Amount is {}{0}'
StringFormat='Amount is \{0\}'
我甚至试图改变绑定属性的数据类型为 INT
,字符串
和双
。似乎没有任何工作。这是一个很常见的情况,但似乎并没有得到支持。
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
属性类型<$ C原因$ C>对象和 Binding.StringFormat
绑定到类型的属性时才使用字符串
。
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
.
正在发生的事情是:
- 的
绑定
是拳击您的MaxLevelOfInvestment
值并将其存储在Label.Content
属性作为盒装十进制值。 - Label控件具有包括
内容presenter
。 模板 - 由于
的ContentTemplate
没有设置,内容presenter
寻找一个的DataTemplate为
键入。当它发现没有,它使用一个默认的模板。小数定义
- presents字符串使用由
内容presenter使用的默认模板标签的
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.
两种解决方案:
- 使用Label.ContentStringFormat代替Binding.StringFormat,或
- 使用的字符串属性,如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}'}" />
注:为简单起见,我在上面的解释忽略了一个细节:在内容presenter
实际上使用自己的模板
和的StringFormat
属性,但装载这些都是自动模板绑定到的ContentTemplate
和<$ C $时C> ContentStringFormat 的标签
的属性,所以它好像在内容presenter
实际上是使用标签的
属性。
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上标签内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!