WPF StringFormat 格式化文本


StringFormat對特定數據格式的轉換

WPF中,對數字/日期等的格式化,可參考此篇博客:https://www.cnblogs.com/zhengwen/archive/2010/06/19/1761036.html

StringFormat對語言項的格式化

1.單個動態數據綁定

例如:

“已使用此軟件 365 天!”,WPF中可如下處理

添加資源項:

1 <system:String x:Key="LangSource1">已使用此軟件 {0} 天!</system:String> 

StringFormat格式化:

1 <TextBlock Text="{Binding UsedDays,StringFormat={StaticResource LangSource1}}"/> 

文本:《365》

StringFormat格式化:

<TextBlock Text="{Binding UsedDays,StringFormat=《{0}》}"  Foreground="#018000"/>

 其它案例:

1 <TextBox Text="{Binding Value, StringFormat={}{0:0000.0}}" /> // 0123.4
2 <TextBox Text="{Binding Value, StringFormat={}{0:####.#}}" /> // 123.4

 

2.多個動態數據綁定

例如:“30/365”

1     <TextBlock>
2         <TextBlock.Text>
3             <MultiBinding StringFormat="{}{0}/{1}">
4                 <Binding Path="LearnedDays" FallbackValue="0" />
5                 <Binding Path="PlanningDays" FallbackValue="0" />
6             </MultiBinding>
7         </TextBlock.Text>
8     </TextBlock>

例如:“已經學習30天,剩余計划學習天數365”

添加資源項:

 1 <system:String x:Key="LangSource5">已經學習{0},剩余計划學習天數{1}</system:String> 

WPF中stringFormat處理:

1     <TextBlock>
2         <TextBlock.Text>
3             <MultiBinding StringFormat="{StaticResource LangSource5}">
4                 <Binding Path="LearnedDays" FallbackValue="0" />
5                 <Binding Path="PlanningDays" FallbackValue="0" />
6             </MultiBinding>
7         </TextBlock.Text>
8     </TextBlock>
1 <TextBox.Text>
2     <MultiBinding StringFormat="姓名:{0}&#x09;{1}">
3         <Binding Path="FristName" />
4         <Binding Path="LastName" />
5     </MultiBinding>
6 </TextBox.Text>

常見的特殊字符:

小於號(<) &lt;
大於號(>) &gt;
&符號(&) &amp;
引號(") &quot;
單引號(') &apos;
回車 &#x000D;
換行 &#x000A;
Tab &#x0009;
空格 &#x0020;

3. 數據格式轉換與動態數據綁定的靈動結合

例如:“學生張三的期末平均成績為93.20分”

添加資源項:

 1 <system:String x:Key="LangSource5">學生{0}的期末平均成績為{1:N2}分</system:String>  

WPF中stringFormat處理:

1     <TextBlock>
2         <TextBlock.Text>
3             <MultiBinding StringFormat="{StaticResource LangSource5}">
4                 <Binding Path="Name"/>
5                 <Binding Path="Score"/>
6             </MultiBinding>
7         </TextBlock.Text>
8     </TextBlock>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM