显示特定时间段的WPF弹出窗口

时间:2015-03-01 19:23:54

标签: c# wpf popup

我无法让弹出窗口在特定时间内保持打开状态。我有一个派生的弹出类,并把它放在Opened事件中。

    private void Popup_Opened(object sender, EventArgs e)
    {
        DispatcherTimer time = new DispatcherTimer();
        time.Interval = TimeSpan.FromSeconds(5);
        time.Start();
        time.Tick += delegate
        {
            this.IsOpen = false;
        };
    }

它工作得很好,但每个会话只有一次。在此之后调用弹出窗口实例时,它会显示闪烁和几秒钟之间的任何内容。谁能明白为什么?

我也尝试在触发弹出窗口而不是弹出窗口的Opened事件中使用相同的代码,即。

        myPopup.IsOpen = true;
        DispatcherTimer time = new DispatcherTimer();
        time.Interval = TimeSpan.FromSeconds(5);
        time.Start();
        time.Tick += delegate
        {
            myPopup.IsOpen = false;
        };

同样的结果。

1 个答案:

答案 0 :(得分:1)

您需要停止计时器,否则它将继续滴答作响并尝试再次关闭弹出窗口。请参阅以下代码。

public class Popupex : Popup
    {
        public Popupex()
        {
            this.Opened += Popupex_Opened;
        }

        void Popupex_Opened(object sender, EventArgs e)
        {
            DispatcherTimer time = new DispatcherTimer();
            time.Interval = TimeSpan.FromSeconds(10);
            time.Start();
            time.Tick += delegate
            {
                this.IsOpen = false;
                time.Stop();
            };
        }
    }