WPF XAML日期時(shí)間字符串的格式化

XAML中的日期格式化跟程序代碼中的格式化很類(lèi)似,但有一些小小的不同:

對(duì)于某些控件我們可以使用ContentStringFormat

  • 指定日期時(shí)間格式的方式:
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:dd MM YYYY HH:mm:ss}" />
  • 使用默認(rèn)日期格式顯示日期的方式(顯示的日期格式會(huì)隨控制面板里的設(shè)置而變,推薦,對(duì)于國(guó)際化的程序顯示格式非常友好):
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:d}" />
  • 使用默認(rèn)時(shí)間格式顯示時(shí)間的方式(顯示的時(shí)間格式會(huì)隨控制面板里的設(shè)置而變,推薦):
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:t}" />
  • 對(duì)于同時(shí)顯示時(shí)間和日期的方式好簡(jiǎn)單,看看下面的代碼:
<Label
    Content="{Binding Path=BirthDate}" 
/>

對(duì)于很多控件我們可以在綁定時(shí)使用StringFormat

  • ListView里要這樣用
  <ListView.View>
    <GridView AllowsColumnReorder="True">
        <GridViewColumn x:Name="colBirthDate" Header="出生日期" 
                        DisplayMemberBinding="{Binding Path=BirthDate, StringFormat='{}{0:t}'}"    
                        Width="Auto"/>
    </GridView>
</ListView.View>
  • 日期的格式化
<TextBlock Text="{Binding Path=BirthDate, StringFormat={}{0:MM/dd/yyyy}}" />
  • 日期時(shí)間的格式化
<TextBlock Text="{Binding Path=BirthDate, StringFormat={}{0:MM/dd/yyyy hh:mm tt}}" />
  • 金額的格式化
<TextBlock Text="{Binding Path=Price, StringFormat={}{0:C}}" />
  • 帶點(diǎn)描述的金額
<TextBlock Text="{Binding Path=Price, StringFormat=價(jià)格:{0:C}}" />
  • 多重綁定及格式化
<Button Content="Delete Me">
    <Button.ToolTip>
        <ToolTip>
            <StackPanel Orientation="Horizontal">
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="Delete {0} {1}">
                            <Binding Path="FirstName" />
                            <Binding Path="LastName" />
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>

鳴謝:

WPF String.Format in XAML with the StringFormat attribute
XAML Using String Format

2020-04-01 無(wú)意間看到此文,大善,附在此處:

WPF中XAML中使用String.Format格式化字符串示例

達(dá)叔傻樂(lè)(darwin.zuo@163.com)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容