I want to be able to set minutes and seconds in a textbox. I now just bind my textbox towards a property, which is a TimeSpan property. So now in my textbox, default is : 00:00:00.
This works fine, but i want to be able to just have 00:00. So that the hours are removed.
How do i do this? I searched the net but can't find any good solution
Thanks!
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" />
If you just wanted one way binding, then you could use StringFormat
:
<TextBlock Text="{Binding MaxTime, StringFormat={}{0:hh\:mm}}" />
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");
}
public object ConvertBack(object value, Type targetType, object parameter,
Globalization.CultureInfo culture)
{
// TODO something like:
return TimeSpan.ParseExact(value, "hh:\mm", CultureInfo.CurrentCulture);
}
}
来源:https://stackoverflow.com/questions/5974763/binding-timespan-in-wpf-mvvm-and-show-only-minutesseconds