从类访问MainWindow变量

时间:2016-03-02 11:36:10

标签: c# wpf

我正在制作一个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类中调用它?

1 个答案:

答案 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

    }
}