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ú)意間看到此文,大善,附在此處:
達(dá)叔傻樂(lè)(darwin.zuo@163.com)