WPF XAML日期时间字符串的格式化

原文: WPF XAML日期时间字符串的格式化

XAML中的日期格式化跟程序代码中的格式化很类似,但有一些小小的不同:

对于某些控件我们可以使用ContentStringFormat

  • 指定日期时间格式的方式:
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:dd MM YYYY HH:mm:ss}" />
  • 使用默认日期格式显示日期的方式(显示的日期格式会随控制面板里的设置而变,推荐,对于国际化的程序显示格式非常友好):
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:d}" />
  • 使用默认时间格式显示时间的方式(显示的时间格式会随控制面板里的设置而变,推荐):
<Label
    Content="{Binding Path=BirthDate}"
    ContentStringFormat="{}{0:t}" />
  • 对于同时显示时间和日期的方式好简单,看看下面的代码:
<Label
    Content="{Binding Path=BirthDate}" 
/>

对于很多控件我们可以在绑定时使用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}}" />
  • 日期时间的格式化
<TextBlock Text="{Binding Path=BirthDate, StringFormat={}{0:MM/dd/yyyy hh:mm tt}}" />
  • 金额的格式化
<TextBlock Text="{Binding Path=Price, StringFormat={}{0:C}}" />
  • 带点描述的金额
<TextBlock Text="{Binding Path=Price, StringFormat=价格:{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

达叔傻乐([email protected])

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12114629.html