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>
    <!--

    -->

效果

相关推荐
步、步、为营2 小时前
.net开源库SignalR
开源·.net
追逐时光者4 小时前
一款开源免费、通用的 WPF 主题控件包
后端·.net
步、步、为营5 小时前
.net开源物联网项目IoTSharp
物联网·开源·.net
百锦再7 小时前
.Net配置文件appsetting.json的几种读取方法
chrome·json·.net·依赖注入·appsetting·web.config
昏睡红猹7 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
张人玉8 小时前
C# 常量与变量
java·算法·c#
就是有点傻9 小时前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子9 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon9 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#