天天看點

WPF中StringFormat的用法

原文:

WPF中StringFormat的用法

WPF中StringFormat的用法可以參照C#中string.Format的用法

1、

C#中用法:

格式化貨币(跟系統的環境有關,中文系統預設格式化人民币,英文系統格式化美元)示例:

string.Format("{0:C}",0.2) 結果為:¥0.10 (英文作業系統結果:$0.10)

預設格式化小數點後面保留兩位小數,如果需要保留一位或者更多,可以指定位數

string.Format("{0:C1}",10.05) 結果為:¥10.1 (截取會自動四舍五入)

格式化多個Object執行個體 string.Format("會員價:{0:C},優惠價{1:C}",99.15,109.25)

WPF中用法:

  格式化貨币示例:

 <TextBox  Name="txtPrice" HorizontalAlignment="Left" Width="170" Height="24" VerticalAlignment="Top" Background="White">

          <TextBox.Text>

                   <Binding Path="Price" StringFormat="{}{0:C}"/>

          </TextBox.Text>

</TextBox>

2、

格式化十進制的數字(格式化成固定的位數,位數不能少于未格式化前,隻支援整形)示例:

string.Format("{0:D3}",99) 結果為:099

string.Format("{0:D2}",1234) 結果為:1234,(精度說明符訓示結果字元串中所需的最少數字個數。)

格式化十進制的數字示例:

 <TextBox  Name="txtRoomCount" HorizontalAlignment="Left" Width="170" Height="24" VerticalAlignment="Top" Background="White">

                   <Binding Path="RoomCount" StringFormat="{}{0:D2}"/>

3、

用分号隔開的數字,并指定小數點後的位數示例:

string.Format("{0:N}", 12300) 結果為:12,300.00  (預設為小數點後面兩位)

string.Format("{0:N3}", 12300.1234) 結果為:12,300.123(自動四舍五入)

同格式化十進制的數字示例

4、

格式化百分比示例:

string.Format("{0:P}", 0.12341) 結果為:12.34% (預設保留百分的兩位小數)

string.Format("{0:P1}", 0.1256) 結果為:12.6% (自動四舍五入)

5、

零占位符和數字占位符示例:

string.Format("{0:0000.00}", 12345.015) 結果為:12345.02

string.Format("{0:0000.00}", 123.015) 結果為:0123.02

string.Format("{0:###.##}", 12345.015) 結果為:12345.02

string.Format("{0:####.#}", 123.015) 結果為:123194

6、

日期格式化示例:

string.Format("{0:d}",System.DateTime.Now) 結果為:2010-6-19 (月份位置不是06)

string.Format("{0:D}",System.DateTime.Now) 結果為:2010年6月19日

string.Format("{0:f}",System.DateTime.Now) 結果為:2010年6月19日 20:30

string.Format("{0:F}",System.DateTime.Now) 結果為:2010年6月19日 20:30:10

string.Format("{0:g}",System.DateTime.Now) 結果為:2010-6-19 20:30

string.Format("{0:G}",System.DateTime.Now) 結果為:2010-6-19 20:30:10

string.Format("{0:m}",System.DateTime.Now) 結果為:6月19日

string.Format("{0:t}",System.DateTime.Now) 結果為:20:30

string.Format("{0:T}",System.DateTime.Now) 結果為:20:30:10

string.Format("{0:yyyy-MM-dd HH:mm}",System.DateTime.Now) 結果為:2010-6-19 20:30

string.Format("{0:yyyy-MM-dd }",System.DateTime.Now) 結果為:2010-6-19

<TextBox  Name="txtCreateTime" HorizontalAlignment="Left" Width="170" Height="24" VerticalAlignment="Top" Background="White">

                   <Binding Path="CreateTime" StringFormat="{}{0:yyyy-MM-dd HH:mm}"/>