How do you tell if a WPF Window is closed?

前端 未结 7 2009
情深已故
情深已故 2020-12-09 07:27

I\'m working on an application that displays some child windows which can either be closed by the user or are automatically closed. While debugging some exceptions that wer

相关标签:
7条回答
  • 2020-12-09 07:41

    I don't know why the IsDisposed property is internal, but if you don't fear reflection:

    var window = new Window();
    var propertyInfo = typeof(Window).GetProperty("IsDisposed", BindingFlags.NonPublic | BindingFlags.Instance);
    var isDisposed = (bool)propertyInfo.GetValue(window);
    

    That being said, reflection is not to be overused because you're no longer protected by the public API of the class. Be sure to use at least unit tests if you go that route.

    0 讨论(0)
  • 2020-12-09 07:42

    According to this conversation on the MSDN WPF forums (see the last post), you can check to see if the IsLoaded is false, which means that the window is "eligible" for unloading its content. I hope that works for you!

    0 讨论(0)
  • 2020-12-09 07:46

    My solution was to simply attach an event to the dialog's Closed event:

    MikesDialog dlg = new MikesDialog();
    dlg.Closed += delegate
    {
        //  The user has closed our dialog.
        validationgDlg = null;
    };
    
    //  ...elsewhere in the code...
    
    if (validationgDlg != null)
    {
         //  Our "MikesDialog" is still open...
         . . .
    }
    
    0 讨论(0)
  • 2020-12-09 07:47

    If you derive from the Window class, you can do this:

    public bool IsClosed { get; private set; }
    
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        IsClosed = true;
    }
    

    It has an advantage over registering for the Closed event - no need to un-register the callback.

    0 讨论(0)
  • 2020-12-09 07:54

    You can add a non static property to the WindowClass bool IsClosed, and set true on the Closed event:

    public partial class MyWindow : Window
    {
        public bool IsClosed { get; set; } = false;
        public MyWindow()
        {
            Closed += MyWindow_Closed;
            InitializeComponent();
        }
    }    
    
    private void MyWindow_Closed(object sender, EventArgs e)
    {
       IsClosed = true;
    }
    
    0 讨论(0)
  • 2020-12-09 07:58

    Hope this is useful for you:

    PresentationSource.FromVisual(window) == null;

    0 讨论(0)
提交回复
热议问题