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

    -->

效果

相关推荐
2501_926227942 小时前
.Net程序员就业现状以及学习路线图(五)
学习·.net
光辉岁月~5 小时前
使用CalcBinding实现复杂逻辑绑定
wpf
土了个豆子的7 小时前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
@areok@8 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
Tiger_shl9 小时前
【.Net技术栈梳理】05-gRPC
.net
时光追逐者10 小时前
C# 哈希查找算法实操
算法·c#·哈希算法
三千道应用题11 小时前
C#语言入门详解(18)传值、输出、引用、数组、具名、可选参数、扩展方法
开发语言·c#
micoos11 小时前
C#-LinqToObject-Element
c#
忧郁的蛋~11 小时前
使用.NET标准库实现多任务并行处理的详细过程
开发语言·c#·.net
sun032211 小时前
使用 javax.net.ssl.HttpsURLConnection 发送 HTTP 请求_以及为了JWT通信选用OSS的Jar的【坑】
http·.net·ssl