Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding timespan in wpf mvvm, and show only minutes:seconds?

I want to be able to show minutes and seconds in a textbox. The TextBox is bound towards a property, which is a TimeSpan. In the textbox, the default is : "00:00:00".

This works fine, but how to show only 00:00 where the hours portion is removed.

How do I do this?

This is my binding:

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}"/>
like image 873
Ruben Avatar asked May 12 '11 07:05

Ruben


1 Answers

If you just wanted one way binding, then you could use StringFormat:

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

If you want bidirectional binding, then I would go for a custom value converter.

[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);
    }
}
like image 96
Drew Noakes Avatar answered Sep 30 '22 19:09

Drew Noakes