如何在 XAML 中格式化 TimeSpan [英] How to format TimeSpan in XAML

查看:53
本文介绍了如何在 XAML 中格式化 TimeSpan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化绑定到 TimeSpan 属性的文本块.如果属性是 DateTime 类型,它会起作用,但如果它是 TimeSpan,它会失败.我可以使用转换器完成它.但我想知道是否有其他选择.

I am trying to format a textblock which is bound to a TimeSpan property. It works if the property is of type DateTime but it fails if it is a TimeSpan. I can get it done using a converter. But I am trying to find out if there is any alternatives.

示例代码:

public TimeSpan MyTime { get; set; }

public Window2()
{
    InitializeComponent();
    MyTime = DateTime.Now.TimeOfDay;
    DataContext = this;
}

Xaml

<TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/>

我希望文本块只显示小时和分钟.但它显示为:

I am expecting the textblock to show only hours and mintes. But it is showing as:

19:10:46.8048860

19:10:46.8048860

推荐答案

在 .NET 3.5 中,您可以改用 MultiBinding

In .NET 3.5 you could use a MultiBinding instead

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}:{1}">
            <Binding Path="MyTime.Hours"/>
            <Binding Path="MyTime.Minutes"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

更新
回复评论.

要确保即使小时或分钟是 0-9 也能输出 2 位数字,您可以使用 {0:00} 而不是 {0}.这将确保 12:01 时间的输出是 12:01 而不是 12:1.
如果要将 01:01 输出为 1:01,请使用 StringFormat="{}{0}:{1:00}"

To make sure you output 2 digits even if hours or minutes is 0-9 you can use {0:00} instead of {0}. This will make sure the output for the time 12:01 is 12:01 instead of 12:1.
If you want to output 01:01 as 1:01 use StringFormat="{}{0}:{1:00}"

并且条件格式可用于去除分钟的负号.我们可以使用 {1:00;00}

And Conditional formatting can be used to remove the negative sign for minutes. Instead of {1:00} we can use {1:00;00}

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:00}:{1:00;00}">
            <Binding Path="MyTime.Hours" />
            <Binding Path="MyTime.Minutes" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

这篇关于如何在 XAML 中格式化 TimeSpan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆