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}"/>
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With