15

Those are my declarations and methods of DispatcherTimer:

private DispatcherTimer DishTimer;
private TimeSpan SpanTime;
private void InitTimer()
{

    DishTimer = new DispatcherTimer();
    DishTimer.Interval = new TimeSpan(0, 0, 0, 1);
    DishTimer.Tick += TimerOnTick;

}
private void TimerOnTick(object sender, object o)
{
    SpanTime = SpanTime.Add(DishTimer.Interval);
    Duration.DataContext = SpanTime;
}        

This is where i call it:

private void CaptureButton_Click(object sender, RoutedEventArgs e)
{
    if ((string) CaptureButton.Content == "Capture")
    {

        CaptureAudio();
        InitTimer();
        DishTimer.Start();

        ProgressRing.IsActive = true;
        CaptureButton.Content = "Stop";
    }
    else
    {
        StopCapture();
        DishTimer.Stop();
        ProgressRing.IsActive = false;
        CaptureButton.Content = "Capture";
    }

}

and here is my xaml code for showing the timer:

<TextBlock Name="Duration" Text="{Binding}"  HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24"></TextBlock>

I am making a voice recording app and i want everytime the user press capture to show a timer. My problem here is that i can't reset it

2 Answers 2

27

Calling Stop() and then Start() should restart the Timer Interval.

Sign up to request clarification or add additional context in comments.

8 Comments

You don't need to call Stop(), calling Start() will be enough to reset the timer.
True, but it doesn't make sense reading the code like that. That is an assumption (shortcut) lazy programmers make and will be weird to anyone new reading the code.
where exactly call Stop() ? i tried between InitTimer() and Start() but it continues counting from where it stopped.
@KazaMaster That is because of another problem. Your math is incorrect. You never reset SpanTime = 0, you keep adding to it...
@Romasz To reset the timer, you need to call Stop() and Start() .NET Reference Source: DispatcherTimer.Start()
|
10

You need to (re)set your SpanTime when you press the Capture-button. just do

SpanTime = new TimeSpan();

it should be reset to zero and start over until you press the button again.

1 Comment

i don't really understand this downvote. sure i didn't answer his question title. but in his description, it looks like he wants to reset the time that is shown for the user. so i supposed my answer is what he was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.