0%

WPF中Binding使用StringFormat格式化字符串

货币格式

1
2
3
4
5
<!-- 默认保留两位小数 输出: $12.34 -->
<TextBlock Text="{Binding Price, StringFormat={}{0:C}}" />

<!-- 保留一位小数 输出: $123.4 -->
<TextBlock Text="{Binding Price, StringFormat={}{0:C1}}" />

固定文字

1
2
3
4
5
6
<!-- 固定前缀 输出: 单价:$12.34 -->
<TextBlock Text="{Binding Price, StringFormat=单价: {0:C}}" />

<!-- 固定后缀 输出: 12.345元 -->
<TextBlock Text="{Binding Price, StringFormat={}{0}元}" />

数字格式化

1
2
3
4
5
6
7
8
9
10
11
<!-- 固定位数,仅支持整形 输出: 086723 -->
<TextBlock Text="{Binding Total, StringFormat={}{0:D6}}" />

<!-- 固定小数点后位数 输出: 8234.9354 -->
<TextBlock Text="{Binding Total, StringFormat={}{0:F4}}" />

<!-- 使用用分割符并指定小数点后位数 输出: 8234.933 -->
<TextBlock Text="{Binding Total, StringFormat={}{0:N3}}" />

<!-- 格式化百分比 输出: 78.9%-->
<TextBlock Text="{Binding Persent, StringFormat={}{0:P1}}" />

占位符

1
2
3
4
<!-- 输出: 0123.46 -->
<TextBox Text="{Binding Price, StringFormat={}{0:0000.00}}" />
<!-- 输出: 123.46 -->
<TextBox Text="{Binding Price, StringFormat={}{0:####.##}}" />

时间日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!-- 输出: 5/4/2015 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:d}}" />
<!-- 输出: Monday, May 04, 2015 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:D}}" />
<!-- 输出: Monday, May 04, 2015 5:46 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:f}}" />
<!-- 输出: Monday, May 04, 2015 5:46:56 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:F}}" />
<!-- 输出: 5/4/2015 5:46 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:g}}" />
<!-- 输出: 5/4/2015 5:46:56 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:G}}" />
<!-- 输出: May 04 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:m}}" />
<!-- 输出: May 04 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:M}}" />
<!-- 输出: 5:46 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:t}}" />
<!-- 输出: 5:46:56 PM -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:T}}" />
<!-- 输出: 2015年05月04日 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy年MM月dd日}}" />
<!-- 输出: 2015-05-04 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd}}" />
<!-- 输出: 2015-05-04 17:46 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd HH:mm}}" />
<!-- 输出: 2015-05-04 17:46:56 -->
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd HH:mm:ss}}" />

多重绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--
\a &#x07; BEL
\b &#x08; BS - Backspace
\f &#x0c; FF - Formfeed
\n &#x0a; LF, NL - Linefeed, New Line
\r &#x0d; CR - Carriage return
\t &#x09; HT - Tab, Horizontal Tabelator
\v &#x0b; VT - Vertical Tabelator
-->
<TextBlock.Text>
<MultiBinding StringFormat="姓名: {0}&#x09;{1}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBlock.Text>