我正在制作一个WPF应用程序来模拟流量。我希望Car
s的反应延迟为1秒,可以改变加速度,而不会停止整个应用程序。为此,我想从elapsed
类中访问Car
变量。 elapsed
变量存储了多长时间。
MainWindow
中的代码:
namespace TrafficTester
{
public partial class MainWindow : Window
{
Timer timer = new Timer();
public MainWindow()
{
InitializeComponent();
//create the timer
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = timerInterval;
timer.Enabled = true;
//...
void OnTimedEvent(object source, ElapsedEventArgs e)
{
timer.Enabled = false; //stop timer whilst updating, so updating won't be called again before it's finished
update(); //
timer.Enabled = true;
elapsed += timerInterval;
}
}
}
Car
类中的代码:
namespace TrafficTester
{
public class Car
{
//...
public void changeAccel(double val)
{
int time = MainWindow.elapsed;
int stop = MainWindow.elapsed + reactDelay;
while (time < stop)
{
time = MainWindow.elapsed;
}
accel = val;
}
}
}
accel
是当前加速度,val
是新加速度。 MainWindow.elapsed
应该从MainWindow调用elapsed
变量,但它不会。我怎样才能从Car
类中调用它?
答案 0 :(得分:1)
我看到至少有两个问题:
- 如果要访问计时器,则需要公开
- 然后您可以通过Mainwindow的实例访问它。
要获得经过的时间,就像你想要的那样,你需要从你那里去ElapsedEventHandler并在那里做定时动作!
public partial class MainWindow : Window
{
public System.Timers.Timer myTimer = new System.Timers.Timer();
public MainWindow()
{
//create the timer
myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Where is it?
myTimer.Interval = 5;
myTimer.Enabled = true;
}
//...
void OnTimedEvent(object source, ElapsedEventArgs e)
{
myTimer.Enabled = false; //stop timer whilst updating, so updating won't be called again before it's finished
//update(); //
myTimer.Enabled = true;
// Timer.Elapsed += 5;
}
}
public class Car
{
public void changeAccel(double val)
{
var myWin = (MainWindow)Application.Current.MainWindow;
int time = myWin.myTimer.Elapsed; //<-- you cannot use it this way
}
}