wpf ContentStringFormat 配置整理

ContentStringFormat 属性在 WPF 中用于格式化绑定到 Content 属性的数据。然而,需要注意的是,并非所有控件都直接支持 ContentStringFormat,特别是像 TextBlock 这样的控件,它使用 Text 属性的 StringFormat 而不是 ContentStringFormat。不过,对于 ContentControl 及其子类(如 LabelButton 等),你可以使用 ContentStringFormat 来格式化显示的内容。

以下是一些示例,展示了如何使用 ContentStringFormat(或对于 TextBlock 使用 StringFormat)来格式化不同类型的数据:

1. 货币格式

对于 doubledecimal 类型的货币值,你可以使用货币格式字符串 "C" 或 "C2"(表示两位小数)。

cs 复制代码
<!-- 使用 ContentStringFormat -->  
<Label Content="{Binding Price}" ContentStringFormat="C" />  
<Label Content="{Binding Price}" ContentStringFormat="C2" />  
  
<!-- 对于 TextBlock,使用 StringFormat -->  
<TextBlock Text="{Binding Price, StringFormat=C}" />  
<TextBlock Text="{Binding Price, StringFormat=C2}" />

2. 数值格式

对于整数或浮点数,你可以使用不同的数值格式字符串。

cs 复制代码
<!-- 整数 -->  
<Label Content="{Binding IntegerValue}" ContentStringFormat="N0" />  
  
<!-- 浮点数,保留两位小数 -->  
<Label Content="{Binding FloatValue}" ContentStringFormat="N2" />  
  
<!-- 百分比 -->  
<Label Content="{Binding Percentage}" ContentStringFormat="P" />  
<Label Content="{Binding Percentage}" ContentStringFormat="P2" />  
  
<!-- 对于 TextBlock -->  
<TextBlock Text="{Binding IntegerValue, StringFormat=N0}" />  
<TextBlock Text="{Binding FloatValue, StringFormat=N2}" />  
<TextBlock Text="{Binding Percentage, StringFormat=P2}" />

3. 日期和时间格式

对于 DateTime 类型的值,你可以使用标准的或自定义的日期和时间格式字符串。

cs 复制代码
<!-- 短日期格式 -->  
<Label Content="{Binding Date}" ContentStringFormat="d" />  
  
<!-- 长日期格式 -->  
<Label Content="{Binding Date}" ContentStringFormat="D" />  
  
<!-- 自定义日期和时间格式 -->  
<Label Content="{Binding DateTimeValue}" ContentStringFormat="yyyy-MM-dd HH:mm:ss" />  
  
<!-- 对于 TextBlock -->  
<TextBlock Text="{Binding Date, StringFormat=d}" />  
<TextBlock Text="{Binding DateTimeValue, StringFormat=yyyy-MM-dd HH:mm:ss}" />

4. 字符串连接

虽然 ContentStringFormatStringFormat 主要用于格式化数值和日期时间,但你也可以通过绑定多个属性并使用字符串格式化来连接它们。不过,这通常需要在后台代码中或使用 MultiBindingStringFormatConverter(或类似的转换器)来实现。不过,对于简单的场景,你可以只绑定一个属性并在 XAML 中使用字符串字面量。

注意:

  • 当使用 ContentStringFormatStringFormat 时,请确保绑定的属性类型与你想要的格式字符串兼容。
  • 对于复杂的格式化需求,可能需要编写自定义的 IValueConverter 并在绑定中使用它。
  • 记住,ContentStringFormat 适用于 ContentControl 及其子类,而 StringFormat 适用于 TextBlockText 属性绑定。
相关推荐
小白18 小时前
WPF自定义Dialog模板,内容用不同的Page填充
wpf
Crazy Struggle1 天前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器
James.TCG2 天前
WPF动画
wpf
He BianGu2 天前
笔记:简要介绍WPF中FormattedText是什么,主要有什么功能
笔记·c#·wpf
脚步的影子2 天前
.NET 6.0 + WPF 使用 Prism 框架实现导航
.net·wpf
jyl_sh2 天前
Ribbon (WPF)
ribbon·wpf·client·桌面程序开发·c/s客户端
wo63704312 天前
[Visual Stuidio 2022使用技巧]2.配置及常用快捷键
c#·.net·wpf
小黄人软件2 天前
wpf 字符串 与 变量名或函数名 相互转化:反射
wpf
界面开发小八哥3 天前
DevExpress WPF中文教程:如何解决排序、过滤遇到的常见问题?(二)
.net·wpf·界面控件·devexpress·ui开发
Vae_Mars3 天前
WPF中图片的宫格显示
wpf