DispatcherTimer停止不停止

时间:2011-11-10 14:08:15

标签: c# .net wpf

更新:我把完整的代码作为参考

我正在尝试使用Dispatcher方法而不是Forms.Timer()

我在方法结束时停止了,但是在停止之前它一直循环多次。出了什么问题?

顺便说一句,我必须提到我在timer if语句中使用MessageBox.Show()。不知道这是不是原因。

    private DispatcherTimer mytimer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();            
    }

    void  mytimer_Tick(object sender, EventArgs e)
    {            
        if (mytimer.Interval == new TimeSpan(0,0,2))
        {
            mytimer.Stop();
            if (textBox1.Text.Length <= 1)
            {
                MessageBox.Show("0");
                mytimer.Stop();
            }
            else
            {
                //do code
                MessageBox.Show("more than 0");
                mytimer.Stop();
            }                
        }

    }

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        mytimer.Interval = new TimeSpan(0, 0, 2);
        mytimer.Tick += new EventHandler(mytimer_Tick);                
        mytimer.Start();        
    }

1 个答案:

答案 0 :(得分:6)

每次更改文本时,都会再次添加事件处理程序 。因此,如果输入5个字符,mytimer_Tick将被调用5次。

要解决此问题,请仅将事件处理程序分配一次,例如,在Window构造函数中:

public Window1() 
{ 
    InitializeComponent(); 

    mytimer.Interval = new TimeSpan(0,0,2); 
    mytimer.Tick += new EventHandler(mytimer_Tick); 
} 

private void txtInput_TextChanged(object sender, EventArgs e) 
{ 
    mytimer.Start(); 
} 
相关问题