c# - 从类访问 MainWindow 变量

标签 c# wpf

我正在制作一个 WPF 应用程序来模拟流量。我希望汽车在改变加速度之前有 1 秒的 react 延迟,而不停止整个应用程序。为此,我想从我的 Car 类访问 elapsed 变量。 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 类中调用它?

最佳答案

我至少看到了两个问题:
- 如果你想访问定时器实例,它需要是公共(public)的。
- 然后您可以通过主窗口的实例访问它。

要获取耗时,就像您可能想要的那样,您需要从 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

    }
}

关于c# - 从类访问 MainWindow 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746088/

相关文章:

c# - VB.net网站转换为C#

c# - 如何创建只读文本框样式

c# - 如何更改 DataGridComboBoxColumn 样式?

wpf - 在TextBox(MVVM)中挂接 key

c# - 将 C 结构从 dll 转换为 C#

c# - 如何将字符串数组更改为不使用循环子句的字符串?可以用LINQ实现吗?

c# - 如何以编程方式从 View 模型中选择 ListView 项?

WPF 当属性值大于一定数量时触发

c# - WPF 绑定(bind)如何区分索引器属性和列表元素?

c# - Exchange Web Services 2010/自动完成或建议的联系人