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

安稳与你 提交于 2019-12-06 03:20:44

问题


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" />

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!