The DurationConverter Class
There is one last small class that demonstrates an interesting feature of WPF data binding called "data conversion." When binding a data source to a target UI element you may often want to format it a little differently. You can do it of course by creating a new class that consumes the original data object and formats it and then bind the UI element to the new object. But, WPF provides a standardized solution in the form of the IValueConverter interface. To use it you implement a value converter class that implements the interface (a Convert() and ConvertBack() methods), decorate it with the ValueConversion attribute and you are good to go. The ConvertBack() method is useful in two-way (or write-only) binding scenarios where you want to update the source object when you modify the value in the UI. The DurationConverter class is used for one-way binding only so the ConvertBack() method just throws a NotImplementedException. The Convert() method takes a TimeSpan value and converts it to a string that displays minutes and seconds (if less than an hour) or hours, minutes and seconds. This is more human-readable and there is no need for a finer resolution for the purpose of the MP3 Duration Converter:
[ValueConversion(typeof(TimeSpan), typeof(string))]
public class DurationConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
var duration = (TimeSpan)value;
var d = new DateTime(duration.Ticks);
string format = "mm:ss";
if (duration.Hours > 0)
format = "hh:mm:ss";
return d.ToString(format);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The DurationConverter is used in the XAML for the text property of the total text box:
<TextBox DockPanel.Dock="Left"
Height="22"
Name="total"
Width="60"
Margin="3"
Text="{Binding Path=Self,
Converter={StaticResource DurationConverter}}"
>
</TextBox>
Conclusion
This article showcased the MP3 duration converter and demonstrated various WPF techniques and practices that cover a lot of ground: UI, asynchronous programming, data binding and multimedia control. In the next article I will tell you what happend when I released the program to my wife (hint: not a lot of gratitude).


