Wpf如何在启动新弹出窗口时自动关闭上一个弹出窗口

时间:2017-05-28 10:52:46

标签: c# wpf popup

我有一个包含popup的窗口。当执行操作时,此弹出窗口调用。现在我想要用户连续insert数据并显示弹出窗口,之前称为弹出窗口关闭。碰撞发生。 我的代码是:

public partial class AvinPopup : Window
{
    static AvinPopup _popup;
    static int timePopup = 0;
    static string textPopUp = "";

    private AvinPopup()
    {
        InitializeComponent();
    }
    private static void StartCloseTimer()
    {
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds((double)timePopup);
        timer.Tick += TimerTick;
        timer.Start();
    }

    private static void TimerTick(object sender, EventArgs e)
    {
        DispatcherTimer timer = (DispatcherTimer)sender;
        timer.Stop();
        timer.Tick -= TimerTick;
        _popup.Close();
        _popup.popup.IsOpen = false;

    }
    public static void Show(string _textPopup, int _timePopup = 3)
    {
        timePopup = _timePopup;
        textPopUp = _textPopup;

        Thread newWindowThread = new Thread(ThreadStartPopup);
        newWindowThread.SetApartmentState(ApartmentState.STA);
        newWindowThread.IsBackground = true;
        newWindowThread.Start();
    }

    private static void ThreadStartPopup()
    {

        _popup = new AvinPopup();
        _popup.popup.VerticalOffset = System.Windows.SystemParameters.PrimaryScreenHeight - 200;
        _popup.popup.HorizontalOffset = 100; /*System.Windows.SystemParameters.PrimaryScreenWidth +100;*/
        _popup.txtPopup.Text = textPopUp;
        _popup.Show();
        StartCloseTimer();
        System.Windows.Threading.Dispatcher.Run();
    }

1 个答案:

答案 0 :(得分:0)

private static readonly ManualResetEventSlim _Blocker = new ManualResetEventSlim(false);

private static void ThreadStartPopup()
{
    _Blocker.Reset();
    System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
    {
        if (_popup != null && _popup.IsOpen)
            _popup.IsOpen = false;

         _Blocker.Set();
    }));

    _Blocker.Wait();
    _popup = new AvinPopup();
    _popup.popup.VerticalOffset = System.Windows.SystemParameters.PrimaryScreenHeight - 200;
    _popup.popup.HorizontalOffset = 100; /*System.Windows.SystemParameters.PrimaryScreenWidth +100;*/
    _popup.txtPopup.Text = textPopUp;
    _popup.Show();
    StartCloseTimer();
    System.Windows.Threading.Dispatcher.Run();
}