开发者

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开发者_JAVA百科. 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);
    }
}


I took a different tact and created a string called TimeElapsed and during a timer tick, I would look at another property which was a StopWatch (set during the timer) and then if changed set the string time for showing on the screen.

private Stopwatch StopWatch { get; set; }
private double TimeElapsedDouble { get; set; }

private string _TimeElapsed;

public string TimeElapsed
{
    get { return _TimeElapsed; }
    set { _TimeElapsed = value; OnPropertyChanged(nameof(TimeElapsed)); }
}
private void timerTick(object sender, EventArgs e)
{
    var timeElapsedDuration = StopWatch.Elapsed.Duration(); // Get the timespan.

    if (TimeElapsedDouble != timeElapsedDuration.TotalSeconds) // A change happened?
    {
        TimeElapsedDouble = timeElapsedDuration.TotalSeconds;
        TimeElapsed = timeElapsedDuration.ToString(@"mm\:ss"); // Answer is here
    }

}

Then just bind it to the control as needed

<Label Content="{Binding TimeElapsed}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜