Sang hoon Kim
Sang hoon Kim

Reputation: 31

Timer interval change event in C# in WPF

I want to adjust the value of the interval as a button event.

When you click the button, the value increases by 1, then reducing to the

interval want to calculate the value in seconds.

This applies not adjust the interval.

    // Button click event
    private void Start_sorting_Click(object sender, RoutedEventArgs e)
    {
            // The currValue the interval value.
            this.CurrentValue.Content = currValue;
            // timer start
            if (_timer.IsEnabled == false)
            {
                timerStatus = 1;
                _timer.Tick += timer_tick;
                _timer.Interval = new TimeSpan(0, 0, currValue);
                _timer.Start();
            }
     }

    private void timer_tick(object sender, EventArgs e)
    {
        traceInfo = this.sortingInfos[this.sortingInfosIndex++];

        // Animation proceeds for about one second.
        start_animation(traceInfo.Position, traceInfo.TargetPosition);

        if (sortingInfosIndex >= sortingInfos.Count)
        {
            _timer.Stop();
        }
    }
    // Button click event, interval up
    private void repeatAddvalueButton_Click(object sender, RoutedEventArgs e)
    {
        currValue++;
        this.CurrentValue.Content = currValue;
        _timer.Interval.Add( new TimeSpan(0, 0, currValue));
    }

    // Button click event, interval down
    private void repeatRemoveValueButton_Click(object sender, RoutedEventArgs e)
    {
        currValue--;
        this.CurrentValue.Content = currValue;
        _timer.Interval.Subtract(new TimeSpan(0, 0, 1));
    }

Upvotes: 0

Views: 1077

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

You assume that the .Add and .Subtract methods modify the existing interval, but they actually return a new interval. Since you aren't storing this anywhere, you are just throwing the add or subtract operation away.

Modify your code to use the new interval that you calculate:

private void repeatAddvalueButton_Click(object sender, RoutedEventArgs e)
{
    currValue++;
    this.CurrentValue.Content = currValue;
    _timer.Interval = _timer.Interval.Add( new TimeSpan(0, 0, currValue));
}

// Button click event, interval down
private void repeatRemoveValueButton_Click(object sender, RoutedEventArgs e)
{
    currValue--;
    this.CurrentValue.Content = currValue;
    _timer.Interval = _timer.Interval.Subtract(new TimeSpan(0, 0, 1));
}

You can see above that I modified it to set the _timer.Interval to the result of the add or subtract method. This will change the interval because it doesn't throw the operation away.

Its important to know what types are mutable (changable) and which types are immutable. A TimeSpan is an immutable object, so operations on it return new TimeSpan objects, it doesn't modify the existing one.

Upvotes: 2

Related Questions