如何在 WPF XAML 的多重绑定中使用 stringformat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11014723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use stringformat in multibinding in WPF XAML
提问by ibrahimyilmaz
As you know StringFormat is of great importance for data representation in WPF. My problem is how to use StringFormat when multibinding in WPF?
如您所知,StringFormat 对于 WPF 中的数据表示非常重要。我的问题是如何在 WPF 中进行多重绑定时使用 StringFormat?
If I give a very simple example:
如果我举一个非常简单的例子:
We have variables,which are A and B and whose values are 10.255555 and 25.6999999
我们有变量,它们是 A 和 B,它们的值是 10.255555 和 25.6999999
And we want to show them 10.2,25.6
?
我们想向他们展示10.2,25.6
?
How can I do this with multibinding? Normally it is piece of cake with ValueConverter
如何使用多重绑定来做到这一点?通常它是 ValueConverter 的小菜一碟
Any help and ideas on this topic will be greately appreciated
任何有关此主题的帮助和想法将不胜感激
回答by Thomas Levesque
Just set the StringFormat
property on the MultiBinding
; use placeholders ({0}, {1}...) for each binding in the multibinding, and include format specifiers if necessary (e.g. F1 for a decimal number with 1 decimal digit)
只需将StringFormat
属性设置在MultiBinding
; 为多重绑定中的每个绑定使用占位符({0}、{1}...),并在必要时包含格式说明符(例如 F1 表示具有 1 个十进制数字的十进制数)
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:F1}{1:F1}">
<Binding Path="A" />
<Binding Path="B" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The {}
part at the beginning is the format string is an escape sequence (otherwise the XAML parser would consider {
to be the beginning of a markup extension)
{}
开头的部分是格式字符串是一个转义序列(否则 XAML 解析器会认为{
是标记扩展的开头)
回答by ibrahimyilmaz
If anyone is looking for "Time Formats" this is for 24hr Clock which is how I came to this post:
如果有人正在寻找“时间格式”,这是 24 小时时钟,这就是我来到这篇文章的方式:
<TextBlock TextAlignment="Center">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:HH:mm} - {1:HH:mm}">
<Binding Path="StartTime" />
<Binding Path="EndTime" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The leading 0: and 1: are the reference to the Bindings
前导 0: 和 1: 是对绑定的引用
[0:hh:mm tt] to display AM/PM
[0:hh:mm tt] 显示 AM/PM
回答by Shawn Kendrot
To simplify you could use two TextBlock/Labels to display the values.
为简化起见,您可以使用两个 TextBlock/Labels 来显示值。
If you are using .Net4, you can bind in a Run Inline element of a TextBlock
如果您使用的是 .Net4,则可以绑定 TextBlock 的 Run Inline 元素
<TextBlock>
<Run Text="{Binding A, StringFormat={}{0:F1}}"/>
<Run Text="{Binding B, StringFormat={}{0:F1}}"/>
</TextBlock>