标签内容上的 WPF StringFormat [英] WPF StringFormat on Label Content

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

问题描述

我想将我的字符串绑定格式化为 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}'

我什至尝试将绑定属性的数据类型更改为 intstringdouble.似乎没有任何效果.这是一个非常常见的用例,但似乎不受支持.

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 属性是 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.

正在发生的事情是:

  1. Binding 将您的 MaxLevelOfInvestment 值装箱并将其存储为 Label.Content 属性作为装箱十进制值.
  2. 标签控件有一个包含 ContentPresenter 的模板.
  3. 由于未设置 ContentTemplateContentPresenter 会查找为 Decimal 类型定义的 DataTemplate.如果没有找到,则使用默认模板.
  4. ContentPresenter 使用的默认模板通过使用标签的 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.

有两种可能的解决方案:

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 实际上使用了它自己的 TemplateStringFormat 属性,但在加载这些自动模板绑定到 LabelContentTemplateContentStringFormat 属性,所以看起来好像 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆