Blind Fury
Blind Fury

Reputation: 469

display WPF popup for specific period

I'm having trouble getting a popup to stay open for a specific duration. I have a derived popup class and have put this in the Opened event.

    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;
        };
    }

It works just fine, but only once per session. Any time the popup instance is called after that, it displays for anything between a mere flicker and a couple of seconds. Can anyone see why?

I have also tried using much the same code in the event that triggers the popup instead of in the Opened event of the popup itself, i.e.

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

Same result.

Upvotes: 2

Views: 2818

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

You need to stop the timer, otherwise it will keep ticking and will try to close the popup again. Refer the below code.

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();
            };
        }
    }

Upvotes: 3

Related Questions