在wpf mvvm中绑定时间跨度,并且仅显示分钟:秒?

2024-01-26

我希望能够在文本框中显示分钟和秒。这TextBox绑定到一个属性,该属性是TimeSpan。在文本框中,默认值为:“00:00:00”。

这工作正常,但如何仅显示删除小时部分的 00:00。

我该怎么做呢?

这是我的绑定:

public TimeSpan MaxTime
{
    get
    {
        if (this.Examination.MaxTime == 0)
            return TimeSpan.Zero;
        else
            return maxTime;
    }
    set
    {
        maxTime = value;
        OnPropertyChanged("MaxTime");
        TimeSpan x;
        this.Examination.MaxTime = int.Parse(maxTime.TotalSeconds.ToString());                              
    }
} 
<TextBox Text="{Binding Path=MaxTime,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>

如果您只想要一种方式绑定,那么您可以使用StringFormat:

 <TextBlock Text="{Binding MaxTime, StringFormat={}{0:hh':'mm':'ss}}" />

如果您想要双向绑定,那么我会选择自定义值转换器。

[ValueConversion(typeof(TimeSpan), typeof(String))]
public class HoursMinutesTimeSpanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                          Globalization.CultureInfo culture)
    {
        // TODO something like:
        return ((TimeSpan)value).ToString("hh':'mm':'ss");
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              Globalization.CultureInfo culture)
    {
        // TODO something like:
        return TimeSpan.ParseExact(value, "hh':'mm':'ss", CultureInfo.CurrentCulture);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在wpf mvvm中绑定时间跨度,并且仅显示分钟:秒? 的相关文章

随机推荐