Search code examples
c#wpfdispatchertimer

changing time interval in dispatcher time


So I am trying to change the time interval for a dispatcher time. I tried to change the timer by using a dependency property.

See below code:

    public static readonly DependencyProperty TimeProperty = DependencyProperty.Register("TimeInterval", typeof(int), typeof(MainWindow));
    private int TimersInterval = 200;
    private int TimeInterval
    {
        get { return (int)GetValue(TimeProperty); }
        set { SetValue(TimeProperty, TimersInterval); }
    }

I have tried to change the TimersInterval when a button is clicked to "fast forward":

            if (TimersInterval <1000)
            {
                TimersInterval += 100;
            }
            else
            {
                MessageBox.Show("Not Legit");
            }

The TimersInterval changes but the timers interval doesnt seem to increase.

Thanks for any help!

edit (sorry forgot to add this):

        aTimer = new System.Windows.Threading.DispatcherTimer();
        aTimer.Interval = new TimeSpan(0, 0, 0, 0, TimersInterval);
        TimerEvent = (s, t) => onTimedEvent(sender, t, newParticle, newEnvironment);
        aTimer.Tick += TimerEvent;

Solution

  • The TimeInterval dependency property is useless here. Just change the Interval property of your DispatcherTimer:

    if (TimersInterval < 1000)
    {
        TimersInterval += 100;
        aTimer.Interval = TimeSpan.FromMilliseconds(TimersInterval);
    }
    ...
    

    Perhaps you do not even need the TimersInterval property:

    if (aTimer.Interval.TotalMilliseconds < 1000)
    {
        aTimer.Interval += TimeSpan.FromMilliseconds(100);
    }