如何将毫秒转换为在XAML中显示mm:ss?

Kur*_*raj 2 c# wpf string-formatting time-format

我想我需要使用StringFormat,但我不知道如何找出格式.

dan*_*ndi 6

如果您的输入值是TimeSpan或DateTime,那么您可以使用简单的格式字符串.但我认为情况并非如此.

据我所知,您需要实现自己的Converter,它将您的值作为参数,并输出格式化的字符串.标准C格式化程序无法进行计算分钟所需的模数等实际计算.

例如:(此代码未经过检查,但即时编写!)

public class MmSsFormatConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Int32 sss = (Int32)value;
        Int32 ss = sss / 1000;
        Int32 mm = ss / 60;
        ss = ss % 60;
        return string.Format(@"{0:D2}:{1:D2}", mm, ss);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Binding.DoNothing; // Thanks to Danny Varod for the suggestion!
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

现在将命名空间添加到XAML,以识别Converter,然后将Converter作为资源添加到XAML中.

然后你可以绑定到转换器,如下所示:

<TextBlock Text="{Binding Milliseconds, Converter={StaticResource MmSsFormatConverter}}" />
Run Code Online (Sandbox Code Playgroud)

请注意,如果执行双向绑定,则需要实现ConvertBack函数.此外,您还可以使用paramater参数传递ConverterParameter,就像格式字符串一样.

您可能希望在我编写的代码上添加类型检查和其他约束.(你将超过59:59的情况怎么样?现在它将进入60:00,事件可以转到123:59)