Code for this post is on GitHub.
I have an application that presents various TimeSpan
properties to a user. The default string conversion isn’t great, in fact for anything other than hh:mm:ss
it isn’t intuitive.
A TimeSpan
of 1 day, 2 minutes, 3 hours, 4 seconds, and 5 milliseconds is shown in the example below:
After a little noodling I found some articles that helped me put together something better (at least for me!).
The first feature is the presentation of a TimeSpan
instance as a string:
The second feature is the ability to convert back from a string. For example, entering a value of 1h, 5s
:
… becomes…
And finally, the property can present an interactive editor via a dropdown:
Here’s an example of how the new classes are used as attributes on a TimeSpan
:
[TypeConverter(typeof(TimeSpanStringConverter))] [Editor(typeof(TimeSpanUIEditor), typeof(UITypeEditor))] [DefaultValue(typeof(TimeSpan), "1.02:03:04.005")] [DisplayName("Custom 1")] public TimeSpan A { get; set; } = new TimeSpan(1, 2, 3, 4, 5);