本文介绍了WPF的StringFormat上标签内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要格式化我的字符串作为金额绑定是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, stringand 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.

正在发生的事情是:


  1. 绑定是拳击您的 MaxLevelOfInvestment 值并将其存储在 Label.Content 属性作为盒装十进制值。

  2. Label控件具有包括内容presenter
  3. 模板
  4. 由于的ContentTemplate 没有设置,内容presenter 寻找一个的DataTemplate为小数定义 键入。当它发现没有,它使用一个默认的模板。

  5. presents字符串使用由内容presenter使用的默认模板标签的 ContentStringFormat 属性。

  1. The Binding is boxing your MaxLevelOfInvestment value and storing it the Label.Content property as a boxed decimal value.
  2. The Label control has a template that includes a ContentPresenter.
  3. Since ContentTemplate is not set, ContentPresenter looks for a DataTemplate defined for the Decimal type. When it finds none, it uses a default template.
  4. The default template used by the ContentPresenter presents strings by using the label's ContentStringFormat 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上标签内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:22