如何从WPF中的另一个窗口停止Dispatch计时器 [英] How to stop Dispatch timer from another window in WPF

查看:214
本文介绍了如何从WPF中的另一个窗口停止Dispatch计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一个窗口停止计时器,但我得到例外,因为

对象引用没有设置为对象的实例。

我的代码是

MainWindow.xaml

 public DispatcherTimer timer = new DispatcherTimer(); 

public MainWindow()
{
InitializeComponent();

timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick + = timer_Tick;
timer.Start();

}

void timer_Tick(object sender,EventArgs e)
{
lblTime.Content = DateTime.Now.ToLongTimeString();
}

private void Button_Click(object sender,RoutedEventArgs e)
{
Window1 obj = new Window1();
obj.ShowDialog();
}





Window1.xaml

公开Window1()
{
InitializeComponent();
}

private void Button_Click(object sender,RoutedEventArgs e)
{
MainWindow obj = new MainWindow();
obj = Application.Current.Windows.OfType< MainWindow>()。SingleOrDefault(x => x.IsActive);
obj.timer.Stop();
}

解决方案

我解决了使用..



((主窗口)(this.Owner))timer.Stop();

i want to stop timer from another window but i am getting exception as
Object reference not set to an instance of an object.
My code is
MainWindow.xaml

public  DispatcherTimer timer = new DispatcherTimer();

       public MainWindow()
       {
           InitializeComponent();

           timer.Interval = TimeSpan.FromSeconds(1);
           timer.Tick += timer_Tick;
           timer.Start();

       }

       void timer_Tick(object sender, EventArgs e)
       {
           lblTime.Content = DateTime.Now.ToLongTimeString();
       }

       private void Button_Click(object sender, RoutedEventArgs e)
       {
           Window1 obj = new Window1();
           obj.ShowDialog();
       }



Window1.xaml

public Window1()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MainWindow obj = new MainWindow();
            obj = Application.Current.Windows.OfType<MainWindow>().SingleOrDefault(x => x.IsActive);
            obj.timer.Stop();
        }

解决方案

I solved using ..

((MainWindow)(this.Owner)).timer.Stop();


这篇关于如何从WPF中的另一个窗口停止Dispatch计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆