WPF文本绑定显示格式StringFormat设置-特殊格式时间日期和多数据绑定

WPF文本绑定显示格式StringFormat设置

特殊格式设置

在Textblock等文本控件中,我们经常要显示一些日期和时间,默认显示的日期,不是我们想要的,所以需要自定义格式,还有多个数据可能需要绑定到一个文本中,都可以通过设置StringFormat来实现

日期/时间

使用系统默认样式

xml 复制代码
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:d}}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:D}}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:m}}" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:M}}" />
<TextBlock Grid.Row="4" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:f}}" />
<TextBlock Grid.Row="5" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:F}}" />
<TextBlock Grid.Row="6" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:g}}" />
<TextBlock Grid.Row="7" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:G}}" />
<TextBlock Grid.Row="8" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:t}}" />
<TextBlock Grid.Row="9" Grid.Column="1" Text="{Binding DtNow, StringFormat={}{0:T}}" />

显示效果如下:

自定义格式:

xml 复制代码
<TextBox Text="{Binding DtNow, StringFormat={}{0:yyyy年MM月dd日}}" />
<TextBox Text="{Binding DtNow, StringFormat={}{0:yyyy-MM-dd}}" />
<TextBox Text="{Binding DtNow, StringFormat={}{0:yyyy-MM-dd HH:mm:ss}}" />
          

也可以简化直接写日期格式

xml 复制代码
  <TextBlock Text="{Binding DtNow,StringFormat='yyyy年MM月dd日'}"/>
  <TextBlock Text="{Binding DtNow,StringFormat='yyyy:MM:dd HH:mm:ss'}"/>

显示效果如下

绑定多个属性(多重绑定)

一个文本控件绑定多个属性合并显示,使用MultiBinding,在StringFormat中设置绑定格式{0}代表第一个属性,{1}代表第二个属性,以此类推

xml 复制代码
 <TextBlock>
     <TextBlock.Text>
         <MultiBinding StringFormat="数据计算:{0}/{1}={2}">
             <Binding Path="Value1" />
             <Binding Path="Value2" />
             <Binding Path="Result" />
         </MultiBinding>
     </TextBlock.Text>
 </TextBlock>

显示效果

多重绑定中的特殊字符

xml 复制代码
    \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
    \v  &#x0b;  VT - Vertical Tabelator 
        &gt;     >(右箭头)

示例:

xml 复制代码
<TextBlock>
     <TextBlock.Text>
         <MultiBinding StringFormat="数据计算:{0}/{1}--&gt;{2}">
             <Binding Path="Value1" />
             <Binding Path="Value2" />
             <Binding Path="Result" />
         </MultiBinding>
     </TextBlock.Text>
 </TextBlock>
    <!--

    -->

效果

相关推荐
周杰伦fans38 分钟前
C# - Task 是什么?想象一下你在餐厅点餐
服务器·开发语言·c#
一只小小汤圆2 小时前
简化点集合 道格拉斯-普克算法(Douglas-Peucker Algorithm)
c#·occ
scixing2 小时前
函数式编程 第八讲 循环者,递归也
开发语言·c#
屠夫3 小时前
SqlSugar的简单使用
c#
dotent·18 小时前
C#基于WPF UI框架的通用基础上位机测试WPF框架
ui·c#·wpf
合作小小程序员小小店19 小时前
桌面开发,超市管理系统开发,基于C#,winform,sql server数据库
开发语言·数据库·sql·microsoft·sqlserver·c#
合作小小程序员小小店20 小时前
桌面开发,在线%超市销售管理%系统,基于vs2022,c#,winform,sql server数据
开发语言·数据库·microsoft·c#
p***32351 天前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
2501_941807261 天前
Java高性能消息队列与Kafka实战分享:大规模消息处理、异步通信与性能优化经验
c#·linq