Binding time in wpf mvvm and show only minutes: seconds?

I want to be able to set minutes and seconds in a text box. Now I just bind the text box to a property, which is a TimeSpan property. So now in my default text box: 00:00:00.

This works great, but I want only 00:00. That the watch has been removed.

How should I do it? I searched the web but did not find a good solution.

Thank!

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 Height="23" HorizontalAlignment="Left" Margin="215,84,0,0" Text="{Binding Path=MaxTime,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" VerticalAlignment="Top" Width="50" />
+5
source share
1 answer

If you just want to bind one way, you can use StringFormat:

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

If you want bi-directional 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");
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              Globalization.CultureInfo culture)
    {
        // TODO something like:
        return TimeSpan.ParseExact(value, "hh:\mm", CultureInfo.CurrentCulture);
    }
}
+9

All Articles