Question

I suppose I need to use StringFormat for this, but I'm out of ideas on how to figure out the format.

Was it helpful?

Solution

If your input value were a TimeSpan or a DateTime, then you could use a simple format string. But I assume that's not the case.

As far as I know you need to implement your own Converter, which will take your value as an argument, and output a formatted string. A standard C formatter can't make actual calculations like modulus which is required to calculate the minutes.

An example: (This code is not checked, but written on the fly!)

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
}

Now add the namespace to your XAML, to recognize the Converter, then add the Converter as a resource in your XAML.

Then you can bind to the converter, something like this:

<TextBlock Text="{Binding Milliseconds, Converter={StaticResource MmSsFormatConverter}}" />

Note that you will need to implement that ConvertBack function if you do two-way binding. And also you can use the paramater argument to pass a ConverterParameter, like a format string.

You might want to add type checks and other constraints on the code I wrote. (What about a situation where you will exceed 59:59? Right now it will go to 60:00, and can event go to 123:59)

OTHER TIPS

If you don't want to create the converter you could also do:

    <TextBox Height="23" Text="{Binding Time, StringFormat={}{0:mm:ss}}" />

Time could be a property in your code behind. Or you can bind it to something else..

There is more examples in here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top